Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
441 views
Welcome To Ask or Share your Answers For Others

1 Answer

  • [string] denotes a Tuple of type string
  • string[] denotes an array of strings

The correct usage of the Tuple in your case would be:

let type2:WithStringArray2 = {
    property: ['someString']
};

See Documentation


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...