gpt4 book ai didi

javascript - TypeScript 错误 : "Type ' number' is not assignable to type '0 | 1 | 2' ". 为什么会出现此错误?

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

我收到一个奇怪的 TypeScript 错误。

我有以下示例:

interface Foo {
prop: 0 | 1 | 2;
}

class Bar implements Foo {
prop = 1;
}

我收到错误:

src/example.ts:6:3 - error TS2416: Property 'prop' in type 'Bar' is not assignable to the same property in base type 'Foo'.
Type 'number' is not assignable to type '0 | 1 | 2'.

6 prop = 1;
~~~~

为什么这段代码会报错?

最佳答案

编辑:

如果适合您的用例,您现在还可以执行以下操作(readonly, as const):

class Bar implements Foo {
readonly prop = 1;
}

class Bar implements Foo {
prop = 1 as const;
}

====

在您的类(class)中,1 被推断为加宽的 number 类型,因为推断一个可变标识符只能采用一个确切的初始值会很奇怪值(value)。在您的界面中,您不是在推断类型,而是在显式注释它(不可避免)。

尝试将 prop = 1 转换为 1 或注释 prop : 1 | 2 | 3 = 1 或使 type oneThroughThree = 1 | 2 | 3; 并使用该别名来注释这两个地方。最好的是,使用数字枚举来涵盖您可接受的值范围,并且可能更具可读性。

关于javascript - TypeScript 错误 : "Type ' number' is not assignable to type '0 | 1 | 2' ". 为什么会出现此错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56346520/

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