laclys / Front-End_practice

Daily practice
5 stars 0 forks source link

typescript tips #158

Open laclys opened 3 years ago

laclys commented 3 years ago

工具类

eg:

interface Props {
  a?: string
  b?: string
  c?: string
}

// 仅保留b,c属性并转为必填
type NewProps1 = Required<Pick<Props, 'b' | 'c'>>

// 需要保留Props的所有属性,但是b,c需要必填
type NewProps2 = Partial<Props> & Required<Pick<Props, 'b' | 'c'>>

eg:

// 简单的限定键和值的类型
type Obj1 = Record<string, string>

// 基于其他类型生成新的类型
type FruitTypes = 'apple' | 'banana' | 'pear'

interface FruitInfo {
  name: FruitTypes
  price: number
}

type Fruits = Record<FruitTypes, FruitInfo>

const fruits: Fruits = {
  apple: {
    name: 'apple',
    price: 10
  },
  banana: {
    name: 'banana',
    price: 11
  },
  pear: {
    name: 'pear',
    price: 12
  }
}

type NewProps = SelectRequired<Props, 'b' | 'c'>; // { a?: string, b: string, c: string, d: string }

// 实现 type SelectRequired<T, K extends keyof T> = Required<Pick<T, K>> & Omit<T, K>


- Exclude<Type, ExcludeUnion>
```typescript
type Exclude<T, U> = T extends U ? never : T;

eg:

// 排除一个具体的值

type T0 = Exclude<"a" | "b" | "c", "a">  // "b" | "c"

// 排除一种类型

type T1 = Exclude<string | number | (() => void), Function>

type Extract<T, U> = T extends U ? T : never;


- NonNullable
过滤掉 Type 中的 null 和 undefined,剩余的类型作为一个新类型返回。其实就是 Exclude 的一种特殊情况。
```typescript
type NonNullable<T> = T extends null | undefined ? never : T

type Parameters<T extends (...args: any) => any> = T extends (...args: infer P) => any ? P : never;


- ReturnType
```typescript
/**

 * Obtain the return type of a function type

 */

type ReturnType<T extends (...args: any) => any> = T extends (...args: any) => infer R ? R : any;
laclys commented 3 years ago

分发条件类型

eg:


type ExcludeTypeKey<K> = K extends "type" ? never : K

type Test = ExcludeTypeKey<"emailAddress" | "type" | "foo">

// => "emailAddress" | "foo"

type ExcludeTypeField<A> = {[K in ExcludeTypeKey<A>]: A[K]}

type Test = ExcludeTypeField<{ type: "LOG_IN"; emailAddress: string }>

// => { emailAddress: string }

inter

它可以在 extends 关键字右侧的类型表达式中的任何位置使用。使用它可以为出现在该位置的任何类型命名

eg:

type Unpack<A> = A extends Array<infer E> ? E : A

type Test = Unpack<Apple[]>

// => Apple

type Test = Unpack<Apple>

// => Apple

type Stairs = Unpack<Apple[] | Pear[]>

// => Apple | Pear

type Flip<T> = T extends [infer A, infer B] ? [B, A] : never

type Stairs = Flip<[Pear, Apple]>

// => [Apple, Pear]

type Union<T> = T extends [infer A, infer A] ? A : never

type Stairs = Union<[Apple, Pear]>

// => Apple | Pear

ref