Search code examples
typescriptjavascript-objects

Why Typescript is not throwing error when an empty array value is assigned to a type of array of non empty objects?


let obj: {
    id_1: number;
    id_2: number;
}[] = [];

TS playground

2 Questions

1)How do I define types if I don't want to allow empty array value?

Array should contain object or objects with both the defined keys id_1 and id_2, but cannot be empty

2)How is this valid typescript and why does the TS compiler not throwing errors when an empty array is passed to a array of object type?


I am new to TS and cannot understand the above behaviour, someone please help.


Solution

  • you can create a specific Type to make an "unemptyable" array. Ref here

    Eg : Ts playground

    EDIT : eg if the playground is not working

    type NonEmptyArrayTest<T> = [T, ...T[]];
    let obj: NonEmptyArrayTest<{
      id_1: number;
      id_2: number;
    }>;