簡體   English   中英

TypeScript 錯誤:“類型 'number' 不可分配給類型 '0 | 1 | 2'”。 為什么我收到這個錯誤?

[英]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;
    ~~~~

為什么這段代碼會給出錯誤?

編輯:

如果適合您的用例,您現在還可以執行以下操作( readonlyas 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 = 1type 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)

https://www.typescriptlang.org/docs/handbook/enums.html

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM