We can declare index signature to force the properties of object to be of specific type such as below
const LOOKUP: {
[key: string]: { name: string, age: number };
} = {
isaac: { name: 'isaac', age: 20 },
whatever: {name: 'whatever', age: 17}
};
However, I would like to restrict the possible values that goes as key, so below is my attempt
Attempt 1
type PossibleName = 'isaac' | 'john';
const LOOKUP: {
[key: PossibleName]: { name: string, age: number };
} = {
isaac: { name: 'isaac', age: 20 },
whatever: {name: 'whatever', age: 17}
};
The attempt above hitting error below
An index signature parameter type cannot be a literal type or generic type. Consider using a mapped object type instead.
Attempt 2
type PossibleName = 'isaac' | 'john';
const LOOKUP: {
[key in PossibleName]: { name: string, age: number };
} = {
isaac: { name: 'isaac', age: 20 },
};
And attempt 2 is hitting error below
Property 'john' is missing in type '{ isaac: { name: string; age: number; }; }' but required in type '{ isaac: { name: string; age: number; }; john: { name: string; age: number; }; }'
I can solve it by making the key optional such as below
type PossibleName = 'isaac' | 'john';
const LOOKUP: {
[key in PossibleName]?: { name: string, age: number };
} = {
isaac: undefined,
};
It does allow to not declare john, but at the same time allowing value undefined for both isaac & john, which is not what I wanted.
My goal is that if I defined isaac, or john, the value should not be accepting undefined, but has to be of type { name: string, age: number}, wondering if that's possible?
Isaac, orjohn, the value should not be acceptingundefined, but has to be of type{ name: string, age: number}, wondering if that's possible?{}andjohn: undefined). Making something optional is the same as allowing its value to beundefined.undefinedto the props, asundefinedis a valid value. Exactly why i felt[key in PossibleName]?sounds weird coz I don't really wanna make it optional, but to restrict the possible values{john: Person} | {isaac: Person}? Or{john: Person} | {isaac: Person} | {john: Person, isaac: Person}?