Reputation: 7264
Lets say we have two interfaces:
interface WithStringArray1 {
property: [string]
}
interface WithStringArray2 {
property: string[]
}
Lets declare some variables of these types:
let type1:WithStringArray1 = {
property: []
}
let type2:WithStringArray2 = {
property: []
}
The first initialisation fails with:
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[]'.
The second one is ok.
What is the difference between [string]
and string[]
?
Upvotes: 36
Views: 7045
Reputation: 49105
[string]
denotes a tuple with exactly one string element. Tuples are ordered lists of items, finite and usually fixed sized.string[]
denotes an array of strings. Arrays will have variable size, including even a size of zero.The correct usage of the Tuple in your case would be:
let type2:WithStringArray2 = {
property: ['someString']
};
See Documentation
Upvotes: 40
Reputation: 30625
if we look tuple with three variable. you can see the difference clearly.
let t: [number, string?, boolean?];
t = [42, "hello", true];
let tuple : [string]
is tuple(string) whereas let arr : string[]
is array of string.
Upvotes: 4