2016-04-20 5 views
12

Допустим, у нас есть два интерфейса:разница между типом [] и [Тип] в машинописи

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[]?

ответ

17
  • [string] обозначает Tuple строкового типа
  • string[] обозначает массив строк

Правильное использование Кортеж в вашем случае будет:

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

См Documentation