Issue
let obj: {
id_1: number;
id_2: number;
}[] = [];
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;
}>;
Answered By - herostoky
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.