0
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.

0

1 Answer 1

1

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;
}>;
Sign up to request clarification or add additional context in comments.

1 Comment

You should include the code in the answer itself in case the links stop working in the future

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.