gpt4 book ai didi

TypeScript:从可区分的联合中推断类型以创建 map ?

转载 作者:行者123 更新时间:2023-12-04 14:03:49 46 4
gpt4 key购买 nike

enum ShapeType { Circle, Square }

interface Circle {
kind: ShapeType.Circle,
radius: number
}

interface Square {
kind: ShapeType.Square,
sideLength: number
}

type Shape = Circle | Square

type WhatShape<T extends ShapeType> // <-- can we do without WhatShape?
= T extends ShapeType.Circle ? Circle
: T extends ShapeType.Square ? Square
: never;

type ShapeMap = {
[K in ShapeType]: (s: WhatShape<K>) => void
}


const handlers: ShapeMap = {
[ShapeType.Circle]: (c: Circle) => {
console.log(c.radius)
},
[ShapeType.Square]: s/*inferred!*/ => {
console.log(s.sideLength)
},
}

playground

这可行,但必须维护 WhatShape 以将枚举映射回形状类型,这有点烦人。

有没有什么方法可以让 TS 从 kind 推断出我们的 ShapeMap 的参数类型?

最佳答案

您可以使用 the Extract<T, U> utility type查找工会成员 T可分配给类型 U .在你的情况下,T将是 discriminated union输入 Shape , 和 U将是一个对象类型,其 kind属性是 ShapeType 的特定成员你正在尝试映射。所以WhatShape<T>可以定义为:

type WhatShape<T extends ShapeType> = Extract<Shape, { kind: T }>

它的行为与您现有的版本相同,无需与 Shape 分开维护:

type ShapeMap = {
[K in ShapeType]: (s: WhatShape<K>) => void
}
/* type ShapeMap = {
0: (s: Circle) => void;
1: (s: Square) => void;
} // same as before */

Playground link to code

关于TypeScript:从可区分的联合中推断类型以创建 map ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69170159/

46 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com