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.
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.
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