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

Categories

0 votes
508 views
in Technique[技术] by (71.8m points)

Difference between type[] and [type] in typescript

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

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

1 Answer

0 votes
by (71.8m points)
  • [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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...