I already know that that keyof TCreate produces literal union of its keys in the type TCreate. But I’m confused about what TCreate[keyof TCreate] represents.
Why do we write it this way?
How does it work in TypeScript?
Why does it produce a union of all possible value types, instead of preserving the mapping between a specific key and its corresponding value type? For example, given this type:
type TCreate = {
id: number;
name: string;
active: boolean;
};
keyof TCreate gives "id" | "name" | "active"
TCreate[keyof TCreate] gives number | string | boolean.
I think I expected it to somehow keep the relationship like
["id", number] | ["name", string] | ["active", boolean]
instead of collapsing everything into a union.
Could someone explain why it works this way??
Object.entries()in the title, but your question has little to do with it. The TypeScript typings forObject.entries()does not produce anything withkeyofin it, and if you want it to, you wouldn't write the type you're talking about. Currently the question is confusing and risks being closed as needing clarification.