Issue
I have a nested object such as:
{
'a': { 123: { 'XYZ': { name: 'thing' } } },
'b': { 456: { 'ZZZ': { name: 'other thing' } } },
}
I want to apply restrictions such that the top level keys can only be 'a' or 'b', the 2nd level object's keys can only be numbers, the 3rd level object's keys can only be strings, and the values of that inner object is an object conforming to a specific interface.
I tried doing:
interface Item {
id: number;
name: string;
}
type ValidKeys = 'a' | 'b';
let items = { [index: ValidKeys] : ([index: number] : ([index : string] : Item)) } = {};
But [index: ValidKeys]
is not allowed, and gives me
An index signature parameter type cannot be a literal type or generic type. Consider using a mapped object type instead.
How can I limit the allowed keys of the top level object?
Solution
The in
keyword should do it:
let items = { [index in ValidKeys]
Playground link with simpler object
EDIT: Link with lesser types
Answered By - Tushar Shahi
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.