首页 文章

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

提问于
浏览
15

可以说我们有两个接口:

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 回答

  • 22

    如果我们用三个变量看元组 . 你可以清楚地看到差异 .

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

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

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

    • string[] 表示字符串数组

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

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

    Documentation

相关问题