Reputation: 602
Edited: Change ids type
I have an array with the following values
const ids: number[] = [45, 56];
const obj: any = {
45: "HELLO",
56: "WORLD",
};
I would like to type the current any
type of my object to restrict it to my ids
array values.
I tried with lookup type but I didn't succeed…
Any idea ?
Regards
Upvotes: 8
Views: 3482
Reputation: 3118
If you need to create a function that returns a type-checkable object with keys that correspond to array:
function indexKeys<K extends string>(keys: readonly K[]) {
type Result = Record<K, number>;
const result: Result = {} as Result;
const {length} = keys;
for (let i = 0; i < length; i++) {
const k = keys[i];
result[k] = i;
}
return result;
};
Here the type-checker will complain:
// Property 'zz' does not exist on type 'Result'.
const {aa, zz} = indexKeys(['aa', 'bb']);
Upvotes: 2
Reputation: 249506
You can use the Record
mapped type. You also need to use a const
assertion to capture the literal types of the array elements:
const ids = [45, 56] as const;
const obj: Record<typeof ids[number], string> = {
45: "HELLO",
56: "WORLD",
};
const obj2: Record<typeof ids[number], string> = {
45: "HELLO",
56: "WORLD",
57: "WORLD", // error
};
Upvotes: 14