简体   繁体   English

打字稿中是否可以有一个联合类型的构造函数对象?

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

I have the following code used for run time type checking by vue.js我有以下代码用于 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.这里 Object 和 Array 是运行时对象,vue.js 用来在运行时做类型检查。 This doesn't actually work because |这实际上不起作用,因为 | is interpreted as an arithmetic operator since Object and Array are values rather than types.被解释为算术运算符,因为 Object 和 Array 是值而不是类型。

Is there someway of constructing an object that can represent the object or array type?有没有办法构造一个可以表示对象或数组类型的对象?

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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