web前端 - 🚌 TS 中的内置工具类型

109 阅读2分钟

1.🚌 keyof

获取通过interface或type类型所有的key. keyof 后面必须是类型,并且只能获取第一级的key.

interface A {
  name: string
}
type B = keyof A
//等同于
type B = 'name'

type C = { [key in keyof A]: number }
//等同于
type C = { name: number }

!!!注意⚠️
keyof any 等同于 = "string|number|symbol" 包括objectboolean

2.🚌 typeof

获取数据类型,用于获取对象,数组、函数、class、枚举等类型

## 对象
const a = { name: "s", age: 12 }
type A = typeof a
// 等同于
type A = { name: string, age: number }

## 枚举
enum A { name, age }

type B = typeof A
// 等同于
const a: B = { name: 0, age: 1 }

## class
class A {
  name: string,
  constructor(name: string){
   this.name = name
  }
}

const getClass = (classa:typeof A,name: string)=>{
    const b = new classa(name)
    console.log(b.name)
}
getClass(A,'class a') // class a

## 函数
function A(name: string): string {
 return name
}

const getName = (fnA: typeof A,name: string) => {
    console.log(fnA(name))
}

getName((name:string)=>name, 'this.a')

## 数组
const a = [1, 2, 'll']
type A = typeof a
// 等同于
type A = (string|number)[]

3. 🚌 Record <K, T>

将k中的所有属性值 转换为T 类型,并返回新的对象类型,K只能是 keyof any.

// 源码
type Record <K extends keyof any, T> = { [P in K]: T }

interface A {
 name: string
}
type B = Record<keyof A, number>
// 等同于
type B = { name: number }

4. 🚌 Pick <T,K,K,...>

源码:从T 类型中选取部分K类型,并返回新的类型, T为常用于对象类型

type Pick<T, K extends keyof T> {
  [P in K]: T[P]
}
interface A {
  name: string;
  age: string;
  job: string
}
type B = Pick<A, 'age', 'name'>
// 等同于
type B = { age: string, name: string }

5. 🚌 Partial<T>

将T 中的所有属性设置为可选

type Partial<T> = { [P in keyof T]?: T[P] }

6. 🚌 Required<T>

将 T 中所有的属性设置为必选

type Required<T> = { [P in keyof T]-?: T[P] }

7. 🚌 Readonly<T>

只读。只作为标识作用。代码改动还是生效的。

interface A {
 readonly name: string 
}

8. 🚌 Exclude<T,U>

从 T 中剔除可以赋值给 U 的类型 。用于 type 命名的类型。(去除 相同的)

type Exclude<T, U> = T extends U ? never : T
type A = Exclude<'a'|'b','a'|'c'>
//等同于
type A = 'b'

9. 🚌 Extract<T,U>

从 T 中提取可以赋值给U的类型

type Extract<T, U> = T extends U ? T : nerver
type A = Extract<'a'|'b','a'|'c'>
// 等同于
type A = 'a'

10. 🚌 Omit<T,K,K,...>

提取 T 中不包括 K 的属性

type Omit<T, K extends keyof any> = Pick<T, Exclude<keyof T,K>>

11. 🚌 NonNullable<T>

去除null 和 undefined 后的新类型

12. 🚌 ReturnType<T>

获取函数返回值的类型

13. 🚌 InstanceType<T>

获取构造函数返回值的类型

14. 🚌 Declare

  1. .d.ts的顶级声明必须以declare开头
  2. delcare声明后,include包含的文件不需要import了,直接就可以引用了。

15. Type 和 Interface 的区别

Type: 基础类型、对象类型、联合类型、元祖、交集
Interface: 对象类型

继承方式
Type: & , 例如: type A = B & C
Interface: extends, 例如: interface A extends B {}

重复命名 Type: 会报错 Interface: 会合并