Record 完成异步数据扁平化
const mid = Symbol("goodid");
interface Pros {
[mid]: number;
name: string;
price: number;
}
type Record<T> = {
[P in keyof any]: T;
}; // Record<T> = {[x: string]: T;}
let goodRecord: Record<Pros> = {};
let good: Pros = { [mid]: 101, name: "大豆", price: 9 };
goodRecord[103] = good;
goodRecord["小麦"] = good;
goodRecord[good[mid]] = good;
console.log("goodRecord:", goodRecord);
/*
goodRecord: {
'101': { name: '大豆', price: 9, [Symbol(goodid)]: 101 },
'103': { name: '大豆', price: 9, [Symbol(goodid)]: 101 },
'小麦': { name: '大豆', price: 9, [Symbol(goodid)]: 101 }
}
*/
上面可以分4步来理解
1、K extends keyof any
2、K extends keyof T
3、P in K
4、K in keyof any
K extends keyof any
type A = {
custname: string;
};
type B = {
custname: string;
age: number;
};
type oneType<K> = K extends keyof any ? K : never;
// 鼠标移动到等号左边就会发现:keyof any TS中就等于string|number|symbol
let count: number = 3;
type a1 = oneType<number>; // number
type a2 = oneType<A>; // never //因为它不属于上面3种类型
K extends keyof T
type twoType<T, K> = K extends keyof T ? K : never;
type b1 = twoType<B, "custname">; // custname类型
type b2 = twoType<B, "xx">; // never
P in K
type threeTestType<K extends keyof any, T> = {
[P in "username" | "age"]: T;
};
type threeType<K extends keyof any, T> = {
[P in K]: T;
};
type c1 = threeTestType<string, B>; //c1 = {username: B; age: B}
type c2 = threeType<string, B>; //c2 = {[x: string]: B;}
//表示可以任意多个名称不限,但类型为字符串
type c3 = threeType<number, B>; //c2 = {[x: number]: B;}
//表示可以任意多个名称不限,但类型为number
//**注意[P in number]**,这个number,也可以是字符串number
type dType = {
name: string;
[x: number]: any;
};
let dobj: dType = {
name: "wangwu",
101: "ere",
"103": "df", //字符串数字也是OK的
//"103x": "df" //字符串就不行
};
//[x: string]可以是字符串类型,数字类型 symbol类型
type daType = {
name: string;
[x: string]: any;
};
let daobj: daType = {
name: "wangwu",
101: "ere", //数字也是OK的
"103": "df",
"103x": "df",
acc: "dfx",
};
K in keyof any
type ec<T> = {
[p in keyof B]: T;
};
// ec<T> = { custname: T; age: T; }
type ec2<T> = {
[p in keyof any]: T;
};
//ec2<T> = {[x: string]: T;} 上面说了keyof any TS中就等于string|number|symbol
//这里之所以变成了[x: string],是因为[x: string]可以是字符串,数字,symbol类型
网友评论