How to get types from both keys and values of an object in TypeScript?

Sometimes, we want to get types from both keys and values of an object in TypeScript.

In this article, we’ll look at how to get types from both keys and values of an object in TypeScript.

How to get types from both keys and values of an object in TypeScript?

To get types from both keys and values of an object in TypeScript, we can use the keyof to return the union type of all the key values of an object.

Then we can use the returned type to get the types of the values with typeof.

For instance, we write

const keyToVal = {
  key1: "myValue1",
  key2: "myValue2",
} as const;

type Keys = keyof typeof keyToVal;
type Values = typeof keyToVal[Keys];

to create the Keys type with keyof typeof KeyToVal to assign Keys to the union type with 'key1‘ and 'key2' as the members of the union.

Then we create the Values type by using typeof keyToVal[Keys] to create a union type of all the values in keyToVal.

So Values is "myValue1" | "myValue2".

Conclusion

To get types from both keys and values of an object in TypeScript, we can use the keyof to return the union type of all the key values of an object.