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?
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.
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.
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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With