type A = 1;
let a: A = 1; // 这里只能是1,不能是其他的
type B = 1 | 2;
let b: B = 1; // 这时候只能是1或者2
keyof
interface A {
username: string
age: number
}
// keyof 会把键取出来作为字面量类型
let a: keyof A = 'username' // 这时候只能是username或者是age
// keyof A 等同于
type B = "username" | "age"
let a: B = 'age' // 这时候只能是username或者是age
// keyof 也可以拿到变量的类型
let a = 'yiqi' // string类型
type B = keyof b; // 这个时候等同于 type B = string
// 再比如
let obj: {
username: 'yingxiaozhu',
age: 20
}
// 使用typeof obj能拿到interface Obj { username: string, age: number }的接口。这时候在使用typof就能将接口转换为字面量类型
let a: keyof typeof obj = 'username' // 这时候只能是username或者是age