假设我们有两个接口:
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]
and string[]
?
-
[string]
表示字符串类型的元组。元组有序的项目列表。有限且通常大小固定。这种类型表示法适用于只有一个字符串元素的元组。
-
string[]
表示字符串数组。数组的大小是可变的。甚至包括零大小。
在您的情况下元组的正确用法是:
let type2:WithStringArray2 = {
property: ['someString']
};
See 文档
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)