I am seeking a method to determine the type of any property within a class or a type.
For instance, if I had the classes PersonClass
and PersonType
, and I wanted to retrieve the type of the nationalId
property, I could achieve this using the following code:
class PersonClass{
name: string
nationalId: number
}
type PersonalType={
name: string
nationalId: string
}
type GetNationalIdType<T> = T extends {nationalId: infer U} ? U : never;
var nId3: GetNationalIdType<PersonClass>
var nId4: GetNationalIdType<PersonalType>
This code works well, where nId3
is of type number
and nId4
is of type string
. However, if I want to retrieve the type of any property without knowing its name beforehand, I attempted the following:
// type GetProp<T, K> = T extends {[key: K]: infer U} ? U : never;
type GetProp<T, K extends string> = T extends {[key: K]: infer U} ? U : never;
var nId1: GetProp<PersonClass, "nationalId">
var nId2: GetProp<PersonalType, "nationalId">
Upon running the above code, I encountered the following results: