Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between type[] and [type] in typescript

Tags:

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

like image 753
Ludevik Avatar asked Apr 20 '16 11:04

Ludevik


People also ask

What is array type in TypeScript?

In typescript, an array is a data type that can store multiple values of different data types sequentially. Similar to JavaScript, Typescript supports array declaration and there are multiple ways to do it. Declaring and Initializing Arrays: We can either use var or let for declaring an array.

What is the difference between a type and an interface in TypeScript?

The typescript type supports only the data types and not the use of an object. The typescript interface supports the use of the object.

What is use of type in TypeScript?

TypeScript is a typed language, where we can specify the type of the variables, function parameters and object properties. We can specify the type using :Type after the name of the variable, parameter or property. There can be a space after the colon.


1 Answers

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

like image 96
haim770 Avatar answered Oct 02 '22 19:10

haim770