typescript - 使用构造枚举的泛型类的类型错误
问题描述
我已经总结了一个我必须以下的案例。类型推断没有像我预期的那样工作,我有三个错误,我已将它们作为注释内联。
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; }
我不清楚为什么这不起作用,因为它看起来相对简单。也许我的方法存在根本缺陷?
解决方案
推荐阅读
- javascript - Vue, how to pass function in props in JSX render?
- excel - Change Range of Numbers to be Negative in VBA
- sql - 为将行拉入列而不进行聚合而编写的查询将列混杂在一起,而不是按顺序列出它们
- npm - How to see the build version of a build project with npm
- php - Woocommerce 店面主题删除购物车页面和结帐上的“可配送”文本
- bash - Why does redirection in `< /dev/urandom tr | tr` work; how does this parse?
- facebook - 如何获取我网站上某个页面的 Facebook 评论
- c++ - 如何使用正确的时区从 XTS 索引中获取数字时间?
- playframework - JPA & Ebean DDL,使用@ElementCollection 注解时如何正确生成id?
- swift - 注册屏幕不会成功切换到新的视图控制器。