T extends object + keyof 组合
2022-03-16 本文已影响0人
wyc0859
keyof 关键字
keyof 表示获取一个:类或者对象类型 或者接口类型的,所有属性名[key]组成的联合类型
let obj = { name: "张三", age: 18 };
console.log(typeof obj); //终端或浏览器省略显示类型是object
//但编辑器中推导出类型为:{name: string; age: number;}
type myobj = typeof obj; //所以可以作为type定义的类型
let my: myobj = { name: "xx", age: 22 }; //name改成namex就会报错,类型不对
type keyofobjtype = keyof myobj; //type keyofobjtype = "name" | "age"
//type keyofobjtype = keyof typeof obj; //合并简写,和上面一样的
//let x1=keyof myobj; //这样是报错的,类型不能当值用
let x2: keyof myobj = "name"; //这样是OK的,但如果改成namex就报错了
获取类属性的 数据类型
class Orders {
static count: number;
constructor(
public orderId: number,
public date: Date,
public custname: string,
public phone: string
) {}
doEat() {}
}
type DeType = Orders["orderId"]; //type DeType = number
extends 获取单个类型
class Cobj<K extends keyofobjtype> {
constructor(public cid: number) {}
}
//上面的K就一定是单个类型name或age
let obja = new Cobj<"age">(3); //改成agex就是报错的
type typCid = Cobj<"age">["cid"]; //type typCid = number
T extends object + extends keyof 组合使用好处
封装,类中对这个属性多方式操作
class Order {
static count: number;
constructor(
public orderId: number,
public name: string,
public phone: string
) {}
doEat() {}
}
class ObjectImpl<T extends object, K extends keyof T> {
object!: T;
key!: K;
constructor(object_: T, key_: K) {
this.object = object_;
this.key = key_;
}
getValue() {
return this.object[this.key];
}
setValue(newVal: T[K]) {
this.object[this.key] = newVal;
}
}
let order = new Order(1, "Lisa", "13911110000");
console.log("写死的方式-order.name:", order.name); //order.name: Lisa
//let objectImpl = new ObjectImpl<Order, "name">(order, "name");//可简写为下行
let objectImpl = new ObjectImpl(order, "name");
//因为构造函数中的T和K推导,所以省略<>中的类型
console.log("传类和属性名获取值-objectImpl.getValue():", objectImpl.getValue());
//objectImpl.getValue(): Lisa
objectImpl.setValue("abc"); //类型一定是order["name"]中的原类型,修改为数字肯定是报错的
console.log("修改后:", objectImpl.getValue());