参考文档:https://www.yuque.com/yuanlaishizijiaxiongdi/gpge7z/vdtiou#lvG9T
is
is操作符用于ts的类型谓词中,实现ts类型保护的一种方式。
例如下面代码
function doSometing(value: string | number) {if (typeof value === 'string') {// TS 可以识别这个分支中 value 是 string 类型的参数(这就叫类型保护)// do something} else {// TS 可以识别这个分支中 value 是 number 类型的参数// do something}}
除去上面这种方式以外,还可以使用TS的类型谓词来实现
/*** 此函数用于判断参数 value 是不是 string 类型** 由于返回类型声明了类型谓词,可以帮助TS在代码分支中进行类型保护(默认返回 boolean 类型是没办法做到的)**/function isString(value: any): value is string {return typeof value === 'string';}function doSometing(value: string | number) {if (isString(value)) {// TS 可以识别这个分支中 value 是 string 类型的参数(这就叫类型保护)} else {// TS 可以识别这个分支中 value 是 number 类型的参数}}
相关练习:https://typescript-exercises.github.io/#exercise=4&file=%2Findex.ts
typeof
在 TS 中,typeof 可以获取一个变量的声明类型;(基本类型必须声明)
const num1: number = 10;const num2: typeof num1 = 10; // num2也是number类型const num1 = 10;const num2: typeof num1 = 100; // // Type '100' is not assignable to type '10'.
对于number string boolean 这些基本类型在没有声明而直接赋值的情况下,都会存在这个问题。但如果是对象类型就不会出现这个问题:
const obj = { a: '1', b: 1, c: [1, '1'] };type Foo = typeof obj;//等价于 type Foo = { a: string, b: number, c: (number | string)[] }const obj1 = {a: '2',b: 2,c: [2,'2']}
keyof
获取对象接口的所有key值
type Obj = { a: string; b: string }type Foo = keyof obj;// type Foo = 'a' | 'b';
in
遍历枚举类型
type Keys = 'a' | 'b' | 'c';type Obj = {[ T in Keys]: string;}// in 遍历 Keys,并为每个值赋予 string 类型// type Obj = {// a: string,// b: string,// c: string// }
TS一些内置类型
Partial
功能是将类型的属性变成可选,注意这是浅Partial
type Partial<T> = {[P in keyof T]?: T[P]};
for example
interface UserInfo {id: string;name: string;}const xiaoming: UserInfo = {name: 'xiaoming'}// error:Property 'id' is missing in type '{ name: string; }' but required in type 'UserInfo'
使用Partial
type NewUserInfo = Partial<UserInfo>;const xiaoming: NewUserInfo = {name: 'xiaoming'}
这个NewUserInfo就相当于
interface NewUserInfo {id?: string;name?: string;}
但Partial
type DeepPartial<T> = {// 如果是 object,则递归类型[U in keyof T]?: T[U] extends object? DeepPartial<T[U]>: T[U]};interface UserInfo {id: string;name: string;fruits: {appleNumber: number;orangeNumber: number;}}type NewUserInfo = DeepPartial<UserInfo>;const xiaoming: NewUserInfo = {name: 'xiaoming',fruits: {orangeNumber: 1,}}
