Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript, restrict keys to array elements

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

like image 562
ScreamZ Avatar asked Jul 10 '19 09:07

ScreamZ


2 Answers

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
};
like image 183
Titian Cernicova-Dragomir Avatar answered Oct 18 '22 23:10

Titian Cernicova-Dragomir


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']); 
like image 20
Igor Sukharev Avatar answered Oct 18 '22 22:10

Igor Sukharev