@daben/type-utility
TypeScript icon, indicating that this package has built-in type declarations

1.0.0 • Public • Published

类型工具库

用法

yarn add @core/type-utility -D
# or
npm i @core/type-utility -D

在全局 ts 文件中引入,一般是 global.d.ts 或 index.d.ts。如果没有的话在 tsconfig.json 中配置一个。

// in global.d.ts

/// <refrence types="@core/type-utility">
// other type

// in xx.ts
type A = Promise<string>
// type B = string
type B = PromiseType<A>

API

OptionalRequired<T, Keys>

部分字段必填

用法:

interface A {
  a?: string
  b?: number
}

/**
 * type B = {
 *   a: string
 *   b?: number
 * }
 */
type B = OptionalRequired<A, 'a'>

OptionalPartial<T, Keys>

部分字段非必填

用法:

interface A {
  a: string
  b: number
}

/**
 * type B = {
 *   a: string
 *   b?: number
 * }
 */
type B = OptionalPartial<A, 'b'>

DeepRequired<T>

递归必填

用法:

interface A {
  a?: string
  b?: {
    c?: boolean
  }
}

/**
 * type B = {
 *   a: string
 *   b: {
 *     c: boolean
 *   }
 * }
 */
type B = DeepRequired<A>

DeepPartial<T>

递归选填

用法:

interface A {
  a: string
  b: {
    c: boolean
  }
}

/**
 * type B = {
 *   a?: string
 *   b?: {
 *     c?: boolean
 *   }
 * }
 */
type B = DeepPartial<A>

Overwrite<T, U>

重写属性

用法:

interface A {
  a: string
  b: {
    c: boolean
  }
}

/**
 * type B = {
 *   a: string
 *   b: number
 * }
 */
type B = Overwrite<
  A,
  {
    b: number
    c: boolean
  }
>

Assign<T, U>

合并覆盖属性

用法:

interface A {
  a: string
  b: {
    c: boolean
  }
}

/**
 * type B = {
 *   a: string
 *   b: number
 *   c: boolean
 * }
 */
type B = Assign<
  A,
  {
    b: number
    c: boolean
  }
>

PromiseType<T>

获取 Promise 结果类型

用法:

type A = Promise<string>
// type B = string
type B = PromiseType<A>

Intersection<T, U>

取交集

用法:

interface A {
  a: string
  b: number
}

interface B {
  a: string
  c: boolean
}

/**
 * type C = {
 *   a: string
 * }
 */
type C = Intersection<A, B>

Union<T, U>

取并集

用法:

interface A {
  a: string
  b: number
}

interface B {
  a: string
  c: boolean
}

/**
 * type C = {
 *   a: string
 *   b: number
 *   c: boolean
 * }
 */
type C = Union<A, B>

NonNullFilter

特殊类型,解决 array.filter(Boolean)类型无法排除 null,undefined 的情况

用法:

// (0 | 1)[]
;([null, 0, 1, undefined] as const).filter(Boolean as any as NonNullFilter)

TruthyFilter

特殊类型,解决 array.filter(Boolean)类型无法排除 falsy 值的情况

用法:

// 1[]
;([null, 0, 1, undefined] as const).filter(Boolean as any as TruthyFilter)

ValueOf<T>

获取值的联合类型

用法:

interface A {
  a: string
  b: number
  c: boolean
}

// type B = string | number | boolean
type B = ValueOf<A>

Readme

Keywords

Package Sidebar

Install

npm i @daben/type-utility

Weekly Downloads

2

Version

1.0.0

License

ISC

Unpacked Size

26.1 kB

Total Files

8

Last publish

Collaborators

  • daben