gpt4 book ai didi

typescript - TypeScript 如何理解这种情况?

转载 作者:行者123 更新时间:2023-12-03 07:58:19 25 4
gpt4 key购买 nike

当将一个unknown类型的变量赋值给另一个变量时,我们应该对unknown变量进行类型检查,但是TypeScript如何理解这个特定的条件呢?看起来它返回一个 boolean 但我认为它更复杂:

let first: unknown = 5;
let second: number;

const result = typeof first === 'number';

if(result){
second = first; // error : Type 'unknown' is not assignable to type 'number'
}

if(typeof first === 'number'){
second = first; // no errors
}

最佳答案

TypeScript added support for indirect expression type narrowing in TypeScript 4.4 after PR #44730 was added 2021 年 6 月。在介绍此功能的注释中,Anders Hejsberg 提到了此功能的局限性(强调并格式化了我的):

Narrowing through indirect-references occurs only when:

  • the conditional-expression or discriminant-property access is declared in a const variable declaration with no type annotation, and...
  • the reference being narrowed is one-of:
    • a const variable or
    • a readonly property or
    • a parameter for which there are no assignments in the function body.

在您的情况下,您的 let first:unknown = 5; 变量的赋值不能与此功能一起使用,因为它是 let 局部变量而不是 const 本地。

因此,如果您将代码更改为使用 constfirst 而不是 letfirst,那么它就可以工作:


const first: unknown = 5;
let second: number;

const result = ( typeof first === 'number' );

if( result ) {
second = first; // OK!
}

if( typeof first === 'number' ) {
second = first; // OK!
}

TypeScript playground link

关于typescript - TypeScript 如何理解这种情况?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/75355670/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com