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

Viewed 3180

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?

2 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]

no, let x: [SomeType] means that x is an Array of 1 element and that element is of type SomeType

if you need to declare an array that contains elements of SomeType just use one of the 2 forms you mentioned, SomeType[] or Array<SomeType>

Related