使用 keyof 运算符获取打字稿类的属性类型 [英] Getting type of a property of a typescript class using keyof operator
问题描述
如 Typescript 文档中关于 keyof
运算符所述,可以使用下面的函数获取对象实例的属性.
As stated in the documentation of Typescript about the keyof
operator, one can get a property of an object instance using the function below.
function getProperty<T, K extends keyof T>(o: T, name: K) {
return o[name];
}
当然,可以通过将return o[name]
替换为return typeof o[name]
来获取属性的类型.有没有办法在不传递任何对象实例的情况下检索属性的类型?
Of course, one can get the type of the property by replacing return o[name]
into return typeof o[name]
. Is there a way to retrieve the type of the property without passing any object instance?
function getPropertyType<T>(name: keyof T) {
// something like T[name]?
}
推荐答案
这是您要找的吗?
type PropType<TObj, TProp extends keyof TObj> = TObj[TProp];
并通过执行以下操作获取对象属性的类型:
and get type of an object property by doing:
type MyPropType = PropType<ObjType, '<key>'>;
和typescript中使用Pick
的方式一样,如果传入了无效的key
会报编译错误.
which is the same as the way of using Pick
in typescript, and it can report compile error if there's any invalid key
passed in.
更新
正如@astoilkov 所建议的,一个更简单的选择是 PropType['key']
.
As @astoilkov suggested, a simpler alternative is PropType['key']
.
这篇关于使用 keyof 运算符获取打字稿类的属性类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!