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.
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.