0.17.1 • Published 2 months ago

@zimi/type-utils v0.17.1

Weekly downloads
-
License
MIT
Repository
github
Last release
2 months ago

@zimi/type-utils

typescript 类型辅助函数

install

yarn add @zimi/type-utils

examples

PickOneOf
StructAs
Or


PickOneOf

from: https://dev.to/maxime1992/implement-a-generic-oneof-type-with-typescript-22em

interface Group {
  num: number[]
  str: string[]
  boo: boolean[]
}

/**
 * PickOneOfGroup is {
 *   num: number[]
 *   str: undefined
 *   boo: undefined
 * } | {
 *   num: undefined
 *   str: string[]
 *   boo: undefined
 * } | {
 *   num: undefined
 *   str: undefined
 *   boo: boolean[]
 * }
 */
type PickOneOfGroup = PickOneOf<Group>

↑ all examples ↑

StructAs

interface Group {
  num: number[]
  str: string[]
  boo: boolean[]
}

/**
 * StructedGroup is {
 *   type: 'num'
 *   value: number[]
 * } | {
 *   type: 'str'
 *   value: string[]
 * } | {
 *   type: 'boo'
 *   value: boolean[]
 * }
  */
type StructedGroup = StructAs<Group, 'type', 'value'>

↑ all examples ↑

Or

interface StringObj {
  a: string
  b: string
}

interface NumberObj {
  b: number
  c: number
}

function test1(input: StringObj | NumberObj) {
  // error: Property 'c' does not exist on type 'StringObj'.ts(2339)
  if (typeof input.c === 'number') {
    console.log(input.b)
  }
}

function test2(input: Or<StringObj, NumberObj>) {
  if (typeof input.c === 'number') {
    // correct: input.b is number
    console.log(input.b)
  }
}

↑ all examples ↑

0.17.1

2 months ago

0.17.0

5 months ago

0.15.0

1 year ago

0.16.0

1 year ago

0.11.0

1 year ago

0.9.0

1 year ago

0.12.0

1 year ago

0.13.0

1 year ago

0.9.1

1 year ago

0.8.0

1 year ago

0.7.0

1 year ago

0.6.0

1 year ago

0.5.0

1 year ago

0.4.0

1 year ago

0.3.0

1 year ago

0.2.0

1 year ago

0.1.16

1 year ago

0.1.10

1 year ago

0.1.9

2 years ago