[英]Typescript function define multiple return type
Hey I am new to typescript and I have function which either returns an object or an array嘿,我是打字稿的新手,我有返回对象或数组的函数
const workspace = (workspace: string) => {
How Can I define a return type for the same我如何定义相同的返回类型
const workspace = (workspace:string): Array | Object => {
is giving following error给出以下错误
Generic type 'Array<T>'
I don't know in advance the structure of the Array and also I am not sure if this is Array | Object
我事先不知道 Array 的结构,也不确定这是否是
Array | Object
Array | Object
or not. Array | Object
与否。
Array
is not a type but type constructor, Array<SomeType>
is a type, that is why you cannot say something returns type constructor, it needs to return specific type. Array
不是类型而是类型构造函数, Array<SomeType>
是一种类型,这就是为什么你不能说 something 返回类型构造函数,它需要返回特定的类型。 If your function is polymorphic and can work with any array you can pass type generic argument to Array
type constructor.如果您的函数是多态的并且可以处理任何数组,您可以将类型泛型参数传递给
Array
类型构造函数。 Consider following code:考虑以下代码:
const workspace = <T>(workspace:string): Array<T> | Object => { ...
Thanks to that you return of workspace
will have specific type applied.因此,您返回
workspace
将应用特定类型。
You can also just pass unknown
or any
if elements are not needed to be known:如果不需要知道元素,您也可以只传递
unknown
或any
:
const workspace = (workspace:string): Array<any> | Object => { ...
One more explanation about type constructors.关于类型构造函数的另一种解释。 Every type definition which is requiring another type as argument is a type constructor, you can think about that as function on types.
每个需要另一种类型作为参数的类型定义都是一个类型构造函数,您可以将其视为类型上的函数。 Consider example:
考虑示例:
type AConstructor<T> = {a: T} // type constructor
type A = AConstructor<string> // evaluates to type {a: string}
Well, Array type is generic, you need to say array of what you're returning.好吧, Array 类型是通用的,你需要说你要返回的数组。
const workspace = (workspace:string): Array<SomeType> | Object => { }
If you really don't know the type of the elements in the array, you need to use unknown
.如果您真的不知道数组中元素的类型,则需要使用
unknown
。
const workspace = (workspace:string): Array<unknown> | Object => { }
Also check this answer to find the difference between Object and object: Difference between 'object' and {} in TypeScript另请检查此答案以找出 Object 和 object 之间的区别: Difference between 'object' and {} in TypeScript
You probably wanted object
.你可能想要
object
。
Try尝试
Array<String>;
if type cant be determined use <any>
如果无法确定类型,请使用
<any>
You can use any
if you don't know what type of data it will return.如果您不知道它将返回什么类型的数据,您可以使用
any
。
const workspace = (workspace:string): Array<any> | Object => {}
-----------------Extra Note------------------ -----------------额外说明------------------
You can use typescript's way to define a function.您可以使用 typescript 的方式来定义函数。 Please refer following code:
请参考以下代码:
workspace(workspace: string): Array<any> | object {
//your code here
// your code here
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.