Bootstrap

typescript学习:关键字,操作符,keyof,in,infer...

本文内容如下

关键字,操作符

如果你都有了答案,可以忽略本文章,或去TS学习地图寻找更多答案


关键字操作符

typeof

JS中的typeof:在运行时判断类型

TS中的typeof:在编译时获取类型

interface Person {
   
    name: string,
    age: number,
}

let person: Person = {
    name: 'tao', age: 18 }

//两者一样
type p1 = typeof person  
type p2 = Person

in:遍历

type Names = "xiaoming" | "zhangsan"

type Obj = {
   
    [k in Names]: k
}

Obj = {
   
	xiaoming: 'xiaoming',
	zhangsan: 'zhangsan'
}

keyof

作用: 获取类,对象,接口的所有属性名组成的 联合类型

// 接口
interface Person {
   
    name: string;
    age: number;
}
type K1 = keyof Person;   // "name" | "age"
type K2 = keyof Person[]; // "length" | "toString" | "pop" | "push" | "concat" | "join" 


;