打字稿中类型[]和[类型]之间的区别

时间:2016-04-20 11:07:55

标签: typescript

让我们说我们有两个接口:

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 个答案:

答案 0 :(得分:22)

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

在你的情况下正确使用元组将是:

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

请参阅Documentation

答案 1 :(得分:0)

如果我们看带有三个变量的元组。您可以清楚看到差异。

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

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

相关问题