【发布时间】: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 }。
防止这种情况的最佳方法是什么?
【问题讨论】:
-
这对于如何让编译器推断字符串文字类型也可能很有用stackoverflow.com/questions/54479507/…
标签: typescript