【问题标题】:Get subset of Union type based on Array values根据数组值获取联合类型的子集
【发布时间】:2020-11-29 18:09:59
【问题描述】:

给定以下类型:

// All possible values
type Alphabet = 'a' | 'b' | 'c' | 'd' | 'e' // ... etc

// Value transformation
type ComputedAlphabet<A extends Alphabet> = {[k in A]: true}

let x: ComputedAlphabet<'a' | 'b'>; // it correctly expects: {a: true, b: true}

我想要一个函数类型,它接受一个字母数组并计算它们的值:

type TransformAlphabet=(chars: Alphabet[]) => ComputedAlphabet<how to get subset of Alphabet based on `chars`???>

理想情况下,我想编写这样的调用并正确推断类型:

let transform: TransformAlphabet
transform(['a']) // should infer {a: true} as a return type

当然,我尝试的第一件事是使用泛型,但不知道如何在生成正确类型的同时使泛型类型可选:

type TransformAlphabet<A extends Alphabet>=(chars: A[]) => ComputedAlphabet<A>

如果我在调用时手动传递 A 泛型类型,这在我的情况下不实用。

【问题讨论】:

    标签: typescript typescript-generics


    【解决方案1】:

    你几乎明白了:

    type TransformAlphabet=<A extends Alphabet>(chars: A[]) => ComputedAlphabet<A>
    

    TS Playground

    【讨论】:

    • 我添加了一个链接。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-02
    相关资源
    最近更新 更多