20

Consider the following Typescript example. The first line results in an error 'type undefined[] is not assignable to type [string]'. The last two lines do compile.

let givesAnError: [string] = [];
let isOK: string[] = [];
let isAlsoOK: [string] = ["foo"];

How do you have to interprete the type definition [string] in Typescript?

2 Answers 2

28

The first (givesAnError) and last (isAlsoOK) are tuples, and the second (isOK) is an array.

With arrays all of your elements are of the same type:

let a: string[];
let b: boolean[];
let c: any[];

But with tuples you can have different types (and a fixed length):

let a: [string, boolean, number];
let b: [any, any, string];

So:

a = ["str1", true, 4]; // fine
b = [true, 3, "str"]; // fine

But:

a = [4, true, 3]; // not fine as the first element is not a string
b = [true, 3]; // not fine because b has only two elements instead of 3

It's important to understand the the javascript output will always use arrays, as there's no such thing as tuple in js.
But for the compilation time it is useful.

Sign up to request clarification or add additional context in comments.

2 Comments

so [string] is just an array with 1 string inside it where string[] is an array of strings of n length
@JasonSebring Right
10

Straight to it

string[] // n-length array, must only contain strings

[string] // must be 1-length array, first element must be a string

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.