首页 > 解决方案 > 根据数组值获取联合类型的子集

问题描述

给定以下类型:

// 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在调用时手动传递泛型类型,这在我的情况下是不切实际的。

标签: typescripttypescript-generics

解决方案


你几乎明白了:

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

TS游乐场


推荐阅读