【发布时间】:2019-06-15 03:49:10
【问题描述】:
我正在尝试在 Typescript 中实现一种伪模式匹配,使用它们对可区分联合的支持,使用匹配函数以及表示匹配表达式分支的对象。
这是我希望能够使用的场景:
type Shape =
| { kind: 'Circle', radius: number }
| { kind: 'Rectangle', height: number, width: number }
function printShape(s: Shape) {
return document.write(
match(s, {
'Circle': c => `Circle(${c.radius})`,
'Rectangle': r => `Rectangle(${r.width} x ${r.height})`
}));
}
我目前对匹配函数定义的尝试如下所示:
function match<T extends { kind: V }, V extends string, R>(
x: T, branches: { [P in T['kind']]: (arg: T & { 'kind': P }) => R }) {
return branches[x.kind](x);
}
这很接近,但不幸的是不太有效;虽然我已成功让编译器抱怨给定匹配的完整性,但分支函数的参数类型不正确:参数c 和r 的类型为any。
我可以将kind 作为硬编码的鉴别器,但我通常不明白在 Typescript 中如何从泛型类型联合中过滤出可能性。例如,我将我的练习浓缩为尝试编写以下内容:
type Where<T, K extends keyof T, V extends T[K]> = ???
我的类型约束是正确的,因为我在编写时从编译器获得了关于我的类型和文字的正确验证:
type Circle = Where<Shape, 'kind', 'Circle'>
但我不明白我可以在该类型表达式的右侧写什么来返回:
{ kind: 'Circle', radius: number }
【问题讨论】:
标签: typescript types discriminated-union