36

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[]?

2 Answers 2

40
  • [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

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

Comments

4

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.

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.