Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is :[Interface] a valid array definition in Typescript?

Tags:

typescript

I have a bunch of code in my typescript codebase like this...

export interface SomeType {
    name: string;
}

export interface SomeComposedType {
    things: [SomeType];
}

This has been working fine but then I started running into issues with

Property '0' is missing in type

and

Argument of type 'SomeType[]' is not assignable to parameter of type '[SomeType]'

I'm really confused about this now. I'm pretty sure that

let x:SomeType[] = []

is equivalent to

let x: Array<SomeType> = []

but is

let x:[SomeType] = []

also equivalent and correct?

like image 273
Michael Dausmann Avatar asked Aug 28 '20 00:08

Michael Dausmann


People also ask

How do you define an array in TypeScript interface?

To define an interface for an array of objects, define the interface for the type of each object and set the type of the array to be Type[] , e.g. const arr: Employee[] = [] . All of the objects you add to the array have to conform to the type, otherwise the type checker errors out.

Can an interface be an array?

It turns out interfaces can be as easily applied for array types as well. They are just super useful as interfaces that define complex types and make arrays type-safe - nothing more, nothing less. Interfaces can define type for both array and its values.


1 Answers

No. [SomeType] represents a tuple type, i.e., an array with exactly one element of SomeType

[string, number], for example, would match an array like ["test", 0]

like image 177
Rubydesic Avatar answered Sep 28 '22 01:09

Rubydesic