【发布时间】:2021-03-12 23:34:20
【问题描述】:
//Type declaration:
interface TickListFilter {
type: "tickList";
value: string;
}
interface ColorFilter {
type: "color"
value: ColorValueType
}
type Filter = TickListFilter | ColorFilter;
...
onValueChange = (filter: Filter, newValue: Filter["value"]) => {
if (filter.type === "tickList") {
// variable 'filter' has TickListFilter type (OK)
// variable 'filter.value' has string type (OK)
// variable newValue has ColorValueType | string. I know why, let's fix it!
}
...
onValueChange = <T extends Filter>(filter: T, newValue: T["value"]) => {
if (filter.type === "tickList") {
// variable 'filter' has Filter type (wrong... i need tick list)
// variable 'filter.value' has string | ColorValueType type (wrong, it should be string)
// variable newValue has ColorValueType | string.
}
我该如何解决这个问题?我知道它为什么会发生,因为 TS 不能通过泛型类型来区分联合。但是有什么解决方法可以像我描述的那样工作吗?
我想使用与 switch-case 类似的结构(不是 if-else only)
【问题讨论】:
标签: typescript typescript-generics