@zimi/type-utils
v0.17.3
Published
type utils
Downloads
11
Readme
@zimi/type-utils
typescript 类型辅助函数
install
yarn add @zimi/type-utils
examples
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>
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'>
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)
}
}