What's the difference between String[] and [String] in typescript ? What is the best option to choose between the two ?
They are not the same!
Update: Since TypeScript 2.7 this is not entirely correct anymore (see below for additions):
string[]
says the variable is an array with values of type string (it can be of any size, even empty).[string]
says the variable is an array of size >= 1 and the first entry is a string
[type]
syntax can be extended, like [type1,type2,type3,typeN]
and then requires the array to have a size of at least N and the first N types are as specified, while the following types are the union of those types.Some different examples that illustrate this issue:
const testA: string[] = []; // good
const testB: [string] = []; // Error, array must have a string at position 0
const testC: [string, number] = ["a", 0]; // good
const testC1 = testC[0]; // testC1 is detected to be string
const testC2 = testC[1]; // testC2 is detected to be number
const testD: [string, number] = ["a", 0, "1"]; // good before 2.7, bad afterwards
const testD1 = testD[2]; // testD1 is detected to be string | number
const testE: [string, number] = ["a", 0, 1]; // good before 2.7, bad afterwards
const testE1 = testE[2]; // testE1 is detected to be string | number
const testF: [string, number] = ["a", 0, null]; // Error, null is not of type string|number
Since TypeScript 2.7
The size is by default fixed. So if you want [string] to allow more than one entry, you need to specify in a very ugly way:
interface MinimumStrTuple extends Array<number | string> {
0: string;
}
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