【问题标题】:React Typescript. What is difference between 'as number' and 'Number()'?反应打字稿。 “作为数字”和“数字()”有什么区别?
【发布时间】:2022-01-05 03:30:28
【问题描述】:

我相信 'strVariable as number' 将 strVariable 转换为数字类型。
但是挣扎了几个小时,我发现它的类型没有改变。
Number(strVariable) 是关键。

'as number' 和 'Number()' 有什么区别?
如果'as number'实际上并没有将类型转换为数字,为什么IDE的类型错误被删除??

const strVariable: string = '';
const numVariable: number = 0;
numVariable = strVariable as unknown as number; // I thought it is converting to number but it wasn't
typeof (strVariable as unknown as number); // string. but type error is gone. How?
typeof (Number(strVariable)) // it do converts to number.

【问题讨论】:

    标签: reactjs typescript types numbers


    【解决方案1】:

    as 关键字只是“告诉编译器这是一个数字”。它不会转换任何东西,该值必须是一个已经存在的数字,否则您会出现异常行为。

    Number() 是一个function,具有精确的行为,可以将相同类型的值转换为数字。

    Es:

    const n: any = 5;
    const s: string = "5";
    
    const a = n as number // <- ok... the type of a was "any", but the content is alredy a number.
    const b = s as number // <- error
    const c = Number(n) // <- ok!
    const d = Number(s) // <- ok, Number() can convert a string onto a number
    

    【讨论】:

      【解决方案2】:

      好的,为了理解我们首先需要澄清 TypeScript 给我们的类型系统在运行时不存在。您可以将其视为变量上有 2 个完全不同的类型层,一个是您期望的类型 - 某种虚拟类型(TypeScript 类型),另一个是它实际所在的类型运行时(JavaScript 类型)。

      typeof 关键字为您提供变量的运行时类型,而as 关键字更改变量的 TypeScript 类型。

      现在我们了解了这一点,我们可以看看您的具体情况。您正在使用属于 TypeScript 并执行“虚拟”转换的 as 关键字。使用它时,您是在告诉 typescript 编译器您希望该变量是一个数字,即使它实际上可能不是一个数字。当使用 typeof 关键字时,您将获得变量的运行时类型,并且因为您只使用了 as 关键字并且没有真正转换它,所以它保持不变。

      在另一个示例中,您使用了 Number() 函数,实际上您在 JavaScript 运行时转换了变量,这意味着变量的实际类型更改为数字,这意味着当您使用typeof关键字你会得到number作为变量的类型。

      希望这已经足够清楚了,如果不是,也许这篇关于 TypeScript 类型转换的文章将有助于澄清一些事情: https://dev.to/ylerjen/typescript-cast-is-a-type-breaker-1jbh

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2015-07-26
        • 2016-09-15
        • 2016-07-08
        • 2017-11-28
        • 2013-09-19
        • 1970-01-01
        相关资源
        最近更新 更多