Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to have a union type constructor object in typescript?

Tags:

typescript

I have the following code used for run time type checking by vue.js

props: {
  foo: Object | Array
}

Here Object and Array are runtime objects, it is used to do type checking at runtime by vue.js. This doesn't actually work because | is interpreted as an arithmetic operator since Object and Array are values rather than types.

Is there someway of constructing an object that can represent the object or array type?

like image 551
jz87 Avatar asked Dec 04 '25 09:12

jz87


1 Answers

You can do

props: {
  foo: {
    type: [Object, Array]
  }
}

or more generally

props: {
  foo: {
    type: [Object as () => YourTypeScriptType, Array, String]
  }
}

It will be like

type FooProps = YourTypeScriptType | Array | string
like image 141
Rémi Becheras Avatar answered Dec 07 '25 00:12

Rémi Becheras