typescript中类型[]和[type]之间的差异

avkwfej4  于 2022-12-05  发布在  TypeScript
关注(0)|答案(2)|浏览(133)

假设我们有两个接口:

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[]之间有什么区别?

7gs2gvoe

7gs2gvoe1#

  • [string]表示字符串类型的Tuple
  • string[]表示字符串数组

在您的情况下,元组的正确用法是:

let type2:WithStringArray2 = {
    property: ['someString']
};

参见文档

ajsxfq5m

ajsxfq5m2#

如果我们看一下三个变量的元组,你就能清楚地看出区别。

let t: [number, string?, boolean?];
t = [42, "hello", true];

let tuple : [string]是元组(字符串),而let arr : string[]是字符串数组。

相关问题