[英]When trying to find the maximum number in TypeScript, I am getting this error: Type 'string' is not assignable to type 'number'
[英]TypeScript error: "Type 'number' is not assignable to type '0 | 1 | 2' ". Why am I getting this error?
我收到一个奇怪的 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;
}
====
在您的课程中, 1
被推断为加宽的number
类型,因为将可变标识符推断为只能采用那个精确的初始值是很奇怪的。 在您的界面中,您不是在推断类型,而是在对其进行显式注释(不可避免)。
尝试将prop = 1 as 1
或注释prop : 1 | 2 | 3 = 1
prop : 1 | 2 | 3 = 1
prop : 1 | 2 | 3 = 1
或type oneThroughThree = 1 | 2 | 3;
type oneThroughThree = 1 | 2 | 3;
并使用该别名来注释这两个地方。 最好的是,使用数字枚举来覆盖您可接受的值范围,并且可能更具可读性。
您还需要在Bar
定义元素,因为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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.