Home > database >  Why does Tuple[number] typecheck but Obj[string] not?
Why does Tuple[number] typecheck but Obj[string] not?

Time:10-19

Given:

type UserObj = { name: string; age: number; role: "admin" | "standard"; };
type ObjValues = UserObj[string];

type UserTuple = [ string, number, "admin" | "standard" ];
type TupleValues = UserTuple[number];

Why does TupleValues type-check but ObjValues not?

EDIT: I’m well aware that I can use keyof

CodePudding user response:

You very probably mean UserObj[keyof UserObj]

CodePudding user response:

UserObj[string] for object that you've defined does not have meaning, the key should be the exact name of the properties for example UserObj["name"] or a union of the object keys "name" | "age" | "role"(you can get union of the object keys by using keyof keyword). But the case for tuples is different UserTuple[number] itself is some kind of a convention to make a union of each one of the tuple members type.

So UserTuple[number] = string | number | "admin" | "standart" which becomes string | number.

  • Related