在我看来,TypeScript不仅将typeof x === 'string'
解释为简单的布尔值,而且还将其解释为某种布尔值is string
类型.
请考虑以下示例:
const tryInference = function(maybeStr?: string): void {
const isStrI = typeof maybeStr === 'string'; // inferred type "is string"
const isStrB: boolean = typeof maybeStr === 'string'; // explicit boolean
console.log( isStrI && maybeStr.charAt(0) ); // <-- ok
console.log( isStrB && maybeStr.charAt(0) ); // <-- TS18048: 'maybeStr' is possibly 'undefined'.
const indeedStr1: string = isStrI ? maybeStr : ''; // <-- ok
const indeedStr2: string = isStrB ? maybeStr : ''; // <-- TS2322: Type 'string | undefined' is not assignable to type 'string'
console.log( indeedStr1, indeedStr2 );
};
我明白,在isStrI
打字的情况下,知道如果是typeof maybeStr === 'string'
,那么maybeStr.charAt
是可用的.
我想,如果是isStrB && maybeStr.charAt(0)
个Typescript ,就会解释为true && maybeStr.charAt(0)
,与typeof maybeStr === 'string'
没有关系了?(if isStrB is true, of course)
这让我想知道:
-
我能以某种方式显式地注释
isStrI
,而不 destructmaybeStr
是string
类型的信息吗? -
我的假设正确吗?有没有人有更详细的解释?