interface Person {
name: string;
age: number;
}
const user: Person = { name: "张三", age: 30 };
type User = typeof user; // type User = Person
const hoel: User = { name: "hoel", age: 5 };
in
用来遍历枚举类型:
type Keys = "a" | "b" | "c";
type Obj = {
[p in Keys]: any;
}; // -> { a: any, b: any, c: any }
keyof
// key of 使用
interface People {
name: string;
age: number;
}
// keyof 取 interface 的键
// type keys = "name" | "age"
type keys = keyof People;
// 假设有一个 object 如下所示,
// 我们需要使用 typescript 实现一个 get 函数来获取它的属性值
const hoel: People = {
name: "hoel",
age: 12,
};
function get<T extends object, K extends keyof T>(o: T, name: K): T[K] {
return o[name];
}
console.log(get(hoel, "age")); // 12
console.log(get(hoel, "name")); // hoel
// error 类型“"address"”的参数不能赋给类型“keyof People”的参数。
console.log(get(hoel, "address"));