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
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
};
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']);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With