【问题标题】:Union types fail as a generic type parameter联合类型作为泛型类型参数失败
【发布时间】:2019-02-01 16:29:49
【问题描述】:

以下代码在我看来是正确的,但是 TypeScript 报告错误:

type AorB = 'a' | 'b';

interface Container {
    aorb: AorB,
};

function example<T>(t: T): T {
    return t;
}

const aorb: AorB = example({ aorb: 'a' });
/*
Type '{ aorb: string; }' is not assignable to type 'AorB'.
  Type '{ aorb: string; }' is not assignable to type '"b"'.
*/

看起来捕获的类型是{ aorb: string },而不是{ aorb: AorB }。 防止这种情况的最佳方法是什么?

查看TypeScript playground

【问题讨论】:

标签: typescript


【解决方案1】:

您的AorB 类型是字符串,但您将对象传递给example。它应该是:

const aorb: AorB = example('a');

const container: Container = example({ aorb: 'a' as 'a' });

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-27
    • 2021-11-11
    • 1970-01-01
    • 2021-11-01
    相关资源
    最近更新 更多