[英]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.