简体   繁体   English

如何使用泛型按名称获取属性的类型

[英]How to get the type of a property by name using generics

I need a way to get the type of any property of a class or a type. 我需要一种方法来获取类或类型的任何属性的类型。

For example if I had the PersonClass and PersonType I want to get the nationalId type. 例如,如果我有PersonClassPersonType我想获得nationalId类型。 I can do this: 我可以做这个:

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>

And it works ok nId3 is a number and nId4 is a string . 它工作正常nId3是一个numbernId4是一个string But If I dont know how to do if I want to get any property. 但如果我想要获得任何财产,我不知道该怎么办。 I try these: 我试试这些:

// 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">

And I get: 我得到:

在此输入图像描述

在此输入图像描述

You just want lookup types . 你只想要查找类型 If T is an object type and K is the type of one of its keys (or a union of such keys), then T[K] is the type of the value for that key (or the union of the value types for those keys): 如果T是一个对象类型而K是其中一个键的类型(或这些键的并集),则T[K]是该键的值的类型(或这些键的值类型的并集) ):

var nId1: PersonClass["nationalId"]; 
var nId2: PersonalType["nationalId"];

If you feel the need to define GetProp , it is pretty straightforward without conditional types: 如果您觉得需要定义GetProp ,那么没有条件类型就非常简单:

type GetProp<T, K extends keyof T> = T[K];

or if you must allow K that is not assignable to keyof T : 或者如果你必须允许K不能分配给keyof T

type GetProp<T, K extends keyof any> = K extends keyof T ? T[K] : never;

or if you really want to use infer and conditional types , you need a mapped type like Record : 或者如果你真的想使用infer条件类型 ,你需要像Record这样的映射类型:

type GetProp<T, K extends keyof any> = T extends Record<K, infer V> ? V : never;

But really the simple lookup type is the way to go, in my opinion. 但在我看来,真正简单的查找类型是要走的路。

Hope that helps. 希望有所帮助。 Good luck! 祝好运!

You need to use the mapped type syntax to do this with conditional types: 您需要使用映射类型语法来执行条件类型:

type GetProp<T, K extends string> = T extends {[key in K]: infer U} ? U : never;

But I think you are really looking for a type query : 但我认为你真的在寻找一个类型查询:

var nId1: PersonClass["nationalId"]
var nId2: PersonalType["nationalId"]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM