![](/img/trans.png)
[英]TypeScript problem inferring value type of restricted conditional key type
[英]Typescript not inferring type with conditional statements
declare const lucky: boolean;
declare const str: string;
declare const nil: null;
const random = lucky ? str : nil;
// random: string | null
if (lucky) {
// random: string | null
// should be string
}
是否有任何解决方法可以达到类似的效果?
这不是 TS 中类型推断的工作方式。
类型检查适用于检查变量,而不适用于可能与检查变量相关的其他变量。
类型推断不适用于变量别名,这是一个更简单的情况。
const lucky: boolean | null = Math.random() < 0.5 ? null : true;
const random = lucky;
if (lucky) {
lucky //this is true
random // this is true | null
}
你可以在这里的操场上看到这个
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.