Skip to content

DataTransferItem Discriminated Union #3

@Offroaders123

Description

@Offroaders123

Realized how to use this in my own projects recently, and now I see that this is what I was looking for a while back to have for the DataTransferItem type. It's API is set up to work great with discriminated unions, but for some reason the standard library doesn't discern the different values against the kind property, while it does mention it in the JSDoc comments also.

DataTransferItem Kind Validation

I made a demo to try and add this functionality myself, but the types don't seem to apply for some reason. It might be that I'm trying to re-assign DataTransferItem with a type declaration instead of an interface one, I'm not completely sure. Either way, this is essentially the shape of what it would look like to enable the discriminated union checking using the kind attribute on the DataTransferItem object.

type DataTransferItem = DataTransferFile | DataTransferString;

interface DataTransferFile {
  readonly kind: "file";
  readonly type: string;
  getAsFile(): File;
  getAsString(callback: null): void;
  webkitGetAsEntry(): FileSystemEntry | null;
}

interface DataTransferString {
  readonly kind: "string";
  readonly type: string;
  getAsFile(): null;
  getAsString(callback: FunctionStringCallback): void;
  webkitGetAsEntry(): null;
}

https://basarat.gitbook.io/typescript/type-system/discriminated-unions

The base type definitions for DataTransfer and it's related APIs are in the DOM API types lib (lib.dom.d.ts), so I think it also may not be applying because of that, since I'm using declare global {} to wrap my custom types. I haven't tried overriding types in other lib definitions yet, so I think it also could be that.

Base DataTransferItem Lib Types

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions