简体   繁体   中英

TypeScript pattern match against a string or Blob (type union = string | Blob)

I've defined a union type,

type TextData = string
type BinaryData = Blob
type DataType = TextData | BinaryData

Which I would like to use in a function

function doSomethingWithData(data: DataType): void {
    if (data instanceof TextData)
      // doesn't work (type being used as a value error)

    if (typeof data === 'Blob')
      // doesn't work (typeof data === 'object')

    if (data instanceof Blob)
      // works, but I don't want to use a type alias
}

Is there anyway of getting this to work or do I need to rethink the design?

I know why it doesn't work, the type alias is compiled away after compilation. But is there another approach?

You must use runtime available variables for runtime checks.

Expose to runtime

You can export BinaryData as a runtime variable

type TextData = string
type BinaryData = Blob
const BinaryData = Blob;
type DataType = TextData | BinaryData

function doSomethingWithData(data: DataType): void {
    if (data instanceof BinaryData) {
      // works
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM