联合类型作为通用类型参数失败

时间:2019-02-01 16:29:49

标签: typescript

以下代码对我来说似乎正确,但是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

中查看

1 个答案:

答案 0 :(得分:3)

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

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

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