gpt4 book ai didi

typescript : Type 'number' is not assignable to type '0'

转载 作者:搜寻专家 更新时间:2023-10-30 21:20:58 25 4
gpt4 key购买 nike

我将变量x 声明为

public x : 0;

而不是将其初始化为 0

认为我已经正确地声明了它,我将它初始化为

this.x = 5;

我在上面的行中遇到了错误,内容是

Type '5' is not assignable to type '0'.ts(2322)

谁能告诉我,为什么会这样?

最佳答案

这是 Typescript 的一个特性,在 : 之后声明了可能的类型,也可能是特定的值。

例如,您还可以将变量限制为特定字符串:

var action : "email" | "sms";

在这种情况下,action = "fax" 会给出一个编译错误。

对于字符串,这称为“字符串文字类型”。对于数字,这称为“数字文字类型”。

因此,在您的情况下,您将其声明为允许值 0 的数字文字类型。

另见 https://www.typescriptlang.org/docs/handbook/advanced-types.html#string-literal-typeshttps://www.typescriptlang.org/docs/handbook/advanced-types.html#numeric-literal-types

因此请注意在 Typescript 中混合使用 =:,因为在这种情况下两者都是正确的 Typescript 但具有不同的行为;)

关于 typescript : Type 'number' is not assignable to type '0' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57441520/

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