TypeScript 错误:“类型‘number’无法分配给类型‘0 | 1 | 2’”。为什么我会收到此错误?

Mik*_*ike 7 javascript typescript

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

我有以下示例:

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

class Bar implements Foo {
  prop = 1;
}

Run Code Online (Sandbox Code Playgroud)

我收到错误:

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;
    ~~~~
Run Code Online (Sandbox Code Playgroud)

为什么这段代码会给出错误?

Jas*_*ban 6

编辑:

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

class Bar implements Foo {
  readonly prop = 1;
}
Run Code Online (Sandbox Code Playgroud)

或者

class Bar implements Foo {
    prop = 1 as const;
}
Run Code Online (Sandbox Code Playgroud)

====

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

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


Get*_*awn 0

您还需要定义该元素,Bar因为它Foo是一个接口:

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

class Bar implements Foo {
  prop: 0 | 1 | 2 = 1;
}
Run Code Online (Sandbox Code Playgroud)

接口只是描述了类的外观,因此基本上您需要重新定义类中的所有内容以匹配您的接口。

如果您不想重新定义元素的定义,则类可能是更好的选择:

class Foo {
  protected prop: 0 | 1 | 2;
}

class Bar extends Foo {
  public test() {
    this.prop = 1;
  }
}
Run Code Online (Sandbox Code Playgroud)