TypeScript条件类类型计算异常:MyUtf解析错误问题求助
TypeScript 类型映射错误:空类实例类型结构兼容导致判断失效
你的代码中MyUtf和MyFloat64都是无属性/方法的空类,而TypeScript采用结构类型系统——只要两个类型的结构完全一致,就会被视为兼容。因此MyUtf extends MyFloat64会被判定为true,导致所有泛型参数都匹配第一个条件,返回number。
以下是两种可行的修复方案:
方案一:给子类添加独特标识属性
通过给每个子类添加唯一的只读字面量属性,让TypeScript能区分它们的结构:
export abstract class DT {} export class MyUtf extends DT { readonly _type = 'utf' as const; } export class MyFloat64 extends DT { readonly _type = 'float64' as const; } type DTtoJs<T extends DT> = T extends MyFloat64 ? number : T extends MyUtf ? string : never; type ShouldBeString = DTtoJs<MyUtf>; // string(符合预期) type ShouldBeNumber = DTtoJs<MyFloat64>; // number(符合预期)
方案二:基于构造函数类型判断
直接将泛型约束为类的构造函数类型(而非实例类型),利用构造函数类型的唯一性做判断:
export abstract class DT {} export class MyUtf extends DT {} export class MyFloat64 extends DT {} type DTtoJs<T extends typeof DT> = T extends typeof MyFloat64 ? number : T extends typeof MyUtf ? string : never; type ShouldBeString = DTtoJs<typeof MyUtf>; // string(符合预期) type ShouldBeNumber = DTtoJs<typeof MyFloat64>; // number(符合预期)
内容的提问来源于stack exchange,提问作者scarf
相关产品推荐
相关产品推荐

