Javascript TypeScript错误:";类型';编号';不可分配给类型';0 | 1 | 2'&引用;。为什么我会犯这个错误?
我收到一个奇怪的打字错误 我举了以下例子:Javascript TypeScript错误:";类型';编号';不可分配给类型';0 | 1 | 2'&引用;。为什么我会犯这个错误?,javascript,typescript,Javascript,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 'numbe
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;
~~~~
为什么此代码会给出错误?您还需要在
栏中定义元素,因为Foo
是一个接口:
interface Foo {
prop: 0 | 1 | 2;
}
class Bar implements Foo {
prop: 0 | 1 | 2 = 1;
}
接口只是描述类的外观,因此基本上需要重新定义类中的所有内容以匹配接口
如果不想重新定义元素的定义,则类可能是更好的选择:
class Foo {
protected prop: 0 | 1 | 2;
}
class Bar extends Foo {
public test() {
this.prop = 1;
}
}
因为您已将prop指定为类型“0”、“1”或“2”,而不是可能的值0、1和2
正确的方法是创建一个可能值为0、1和2(例如枚举值)的枚举类型变量,并分配prop以假定枚举类型值(例如prop:values)
编辑:
如果符合您的用例,您现在还可以执行以下操作(readonly
,as const
):
class Bar implements Foo {
readonly prop = 1;
}
或
====
在您的类中,1
被推断为加宽的number
类型,因为推断一个可变标识符只能获取一个精确的初始值是很奇怪的。在您的接口中,您不是在推断类型,而是在显式地(不可避免地)注释它
尝试将prop=1转换为1
或注释prop:1 | 2 | 3=1
或使键入onethrothThree=1 | 2 | 3
并使用该别名对这两个位置进行注释。最好的方法是,使用数字枚举覆盖可接受值的范围,这样可能更容易阅读。试试prop:0 | 1 | 2=1
;通过接口/超类定义的类型来上下文化类型实现/子类属性。不幸的是,这并没有发生。因此,Bar
中的prop
的推断类型被扩大为number
。您必须提示编译器使其保持狭窄,如TS3.4或更高版本中的prop=1作为const
,或prop=1作为Foo['prop']
,或readonly prop=1
,如果您不打算更改它。祝你好运。是的,我可以用这种方法修好它。但是为什么我要显式地指定类型呢?这是一种令人困惑的行为。我指定我的类实现接口。在这个界面中,我清楚地描述了我想要的类型和属性。然后在实现这个接口的类中,我得到了不同的类型(在这个例子中,扩展的数字)。我在下面的示例中理解了类型加宽的工作原理:constnumericliteral=42;设WidedNumericLiteral=numericLiteral代码>但是为什么我在实现接口的类中有类型加宽?也许对于实现多个接口的类的一般情况,将它们相交以决定如何以这种方式扩展类成员的类型推断还没有解决,因为太复杂了?我不知道。也许在github上请求该功能,至少得到一个基本原理(或者一个dupe标签)。
class Bar implements Foo {
prop = 1 as const;
}