5

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 2

14

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]

3
  • 1
    oh wow, now this message makes sense Type '[]' is not assignable to type '[SomeType]'. Source has 0 element(s) but target requires 1.(2322) #ivebeendoingitwrong Aug 28, 2020 at 0:18
  • 1
    Consider providing a documentation link for tuples in this answer. Cheers!
    – jcalz
    Aug 28, 2020 at 0:19
  • I was getting mixed up with GraphQL's array syntax! Thx!
    – WebSpence
    Feb 27, 2021 at 1:06
8

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>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.