2016-04-20 24 views
12

phép nói rằng chúng tôi có hai giao diện:Sự khác nhau giữa loại [] và [loại] trong nguyên cảo

interface WithStringArray1 { 
    property: [string] 
} 

interface WithStringArray2 { 
    property: string[] 
} 

Cho phép khai báo một số biến của các loại sau:

let type1:WithStringArray1 = { 
    property: [] 
} 

let type2:WithStringArray2 = { 
    property: [] 
} 

Các khởi động đầu tiên không thành công với:

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[]'. 

Điều thứ hai là ok.

Sự khác nhau giữa [string]string[] là gì?

Trả lời

17
  • [string] biểu thị một Tuple kiểu string
  • string[] biểu thị một mảng của chuỗi

Việc sử dụng chính xác của các tuple trong trường hợp của bạn sẽ là:

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

Xem Documentation

Các vấn đề liên quan