Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Typescript what does Record<K extends keyof any, T> mean? [duplicate]

Tags:

typescript

I came across this code -

type Record<K extends keyof any, T> = {
    [P in K]: T;
};

Here, I understand that T> is a generic type assertion.

Can someone please explain what is K? And please explain what this function returns with a sample i/o?

Thanks in anticipation.

like image 635
Jananie Balaji Avatar asked Oct 24 '25 06:10

Jananie Balaji


1 Answers

First, keyof returns a union of all keys of a type.

type BadVector = { x: string, y: boolean }
keyof BadVector // "x" | "y"

So, K extends keyof any says that K is such a keyof union type. For example, the type keyof BadVector would extend keyof any.

Second, a mapped type maps all keys of an object to a new value type. So [P in K]: T means: Map each property P in K to a value type T.

For example, take the example from the documentation:

interface CatInfo {
  age: number;
  breed: string;
}
 
type CatName = "miffy" | "boris" | "mordred";
 
const cats: Record<CatName, CatInfo> = {
  miffy: { age: 10, breed: "Persian" },
  boris: { age: 5, breed: "Maine Coon" },
  mordred: { age: 16, breed: "British Shorthair" },
};

The type of cats is Record<CatName, CatInfo>. This means that for all types in CatName, a value with the type CatInfo must be provided.

like image 62
linuskmr Avatar answered Oct 25 '25 22:10

linuskmr