ts keyof

ts中keyof的作用

keyof用于获取对象索引,或者简单的说获取属性名

例如

interface User{
	id?:number,
	name?:string
}

keyof User的结果就是'id'和'name'

ts中字符串可以作为类型

这里的字符串不指string,而是'id'和'name';
从而可以应用在泛型类中实现类似反射的效果:

class Utils{
	static get<K extends keyof User>(propName:K):User[K]{
		return ...;
	}
}

因为限制了get函数的参数类型只能是K,因此propName的值也只能限制在'id'和'name'之间;

Utils.get('id') //正确
Utils.get('name')  //正确

Utils.get('gender') //错误

扩展

ts中本身内置了很多根据keyof扩展的类,理解了keyof的原理就理解了这些类型的意义
例如
注:下面这段代码截取自TypeScript源码

/**
 * Make all properties in T optional
 */
type Partial<T> = {
    [P in keyof T]?: T[P];
};

/**
 * Make all properties in T required
 */
type Required<T> = {
    [P in keyof T]-?: T[P];
};

/**
 * Make all properties in T readonly
 */
type Readonly<T> = {
    readonly [P in keyof T]: T[P];
};

/**
 * From T, pick a set of properties whose keys are in the union K
 */
type Pick<T, K extends keyof T> = {
    [P in K]: T[P];
};

/**
 * Construct a type with a set of properties K of type T
 */
type Record<K extends keyof any, T> = {
    [P in K]: T;
};
posted @ 2022-07-27 14:13  涯唰  阅读(979)  评论(0)    收藏  举报