首页 > 解决方案 > 使用构造枚举的泛型类的类型错误

问题描述

我已经总结了一个我必须以下的案例。类型推断没有像我预期的那样工作,我有三个错误,我已将它们作为注释内联。

enum Type { A = 'A', B = 'B' }

interface ThingA { type: Type.A; }
interface ThingB { type: Type.B; }

type Thing<T extends Type> =
  T extends Type.A ? ThingA :
  T extends Type.B ? ThingB :
  never;

class Wrapper<T extends Type> {
  type: T;

  constructor(thing: Thing<T>) {
    // Type 'Type' is not assignable to type 'T'
    this.type = thing.type;
  }
}

function run<T extends Type>(wrapper: Wrapper<T>): T {
  switch (wrapper.type) {
    // Argument of type 'Wrapper<T>' is not assignable to parameter of type 'Wrapper<Type.A>'.
    // Type 'T' is not assignable to type 'Type.A'.
    // Type 'Type' is not assignable to type 'Type.A'.
    case Type.A: return getTypeA(wrapper);

    // Same error as above but with Type.B
    case Type.B: return getTypeB(wrapper);
  }
}

function getTypeA(wrapper: Wrapper<Type.A>) { return wrapper.type; }
function getTypeB(wrapper: Wrapper<Type.B>) { return wrapper.type; }

我不清楚为什么这不起作用,因为它看起来相对简单。也许我的方法存在根本缺陷?

标签: typescript

解决方案


推荐阅读