[英]Typescript different arrays in object
I have an object for instance:例如,我有一个对象:
const obj = {
arr1: [100, 30, 10],
arr2: ['hello', 'hello', 'hello']
}
Typescript can't define type of obj, what type shouled I assign to obj?打字稿无法定义 obj 的类型,我应该为 obj 分配什么类型? I tried我试过
const obj: [number,number,number] | [string,string,string] {}
but it didn't work, TS2322 error, any suggestions?但它不起作用,TS2322错误,有什么建议吗?
In the example type annotation obj: [number,number,number] | [string,string,string]
在示例中类型注释obj: [number,number,number] | [string,string,string]
obj: [number,number,number] | [string,string,string]
typescript cannot see that you meant an object - it thinks you meant obj
is either a three-tuple of numbers, or a three-tuple of strings. obj: [number,number,number] | [string,string,string]
打字稿看不出你的意思是一个对象——它认为你的意思是obj
要么是一个三元组的数字,要么是一个三元组的字符串。
I'm guessing you want something more like this:我猜你想要更像这样的东西:
// inferred type is { arr1: number[], arr2: string[] }
const obj1 = {
arr1: [100, 30, 10],
arr2: ['hello', 'hello', 'hello']
}
// no compiler error because obj2 matches obj1
const obj2: { arr1: number[]; arr2: string[]; } = obj1
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.