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[]
?
In typescript, an array is a data type that can store multiple values of different data types sequentially. Similar to JavaScript, Typescript supports array declaration and there are multiple ways to do it. Declaring and Initializing Arrays: We can either use var or let for declaring an array.
The typescript type supports only the data types and not the use of an object. The typescript interface supports the use of the object.
TypeScript is a typed language, where we can specify the type of the variables, function parameters and object properties. We can specify the type using :Type after the name of the variable, parameter or property. There can be a space after the colon.
[string]
denotes a Tuple
of type stringstring[]
denotes an array of stringsThe correct usage of the Tuple in your case would be:
let type2:WithStringArray2 = { property: ['someString'] };
See Documentation
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With