【发布时间】: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