可以说我们有两个接口:
interface WithStringArray1 {
property: [string]
}
interface WithStringArray2 {
property: string[]
}
让我们声明一些这些类型的变量:
let type1:WithStringArray1 = {
property: []
}
let type2:WithStringArray2 = {
property: []
}
第一次初始化失败了:
TS2322: Type '{ property: undefined[]; }' is not assignable to type 'WithStringArray1'.
Types of property 'property' are incompatible.
Type 'undefined[]' is not assignable to type '[string]'.
Property '0' is missing in type 'undefined[]'.
第二个是好的 .
[string]
和 string[]
之间有什么区别?
2 回答
如果我们用三个变量看元组 . 你可以清楚地看到差异 .
let tuple : [string]
是元组(字符串),而let arr : string[]
是字符串数组 .[string]
表示字符串类型的Tuple
string[]
表示字符串数组在你的情况下正确使用元组将是:
见Documentation