簡體   English   中英

Typescript:通用類類型推斷

[英]Typescript: Generic class type inference

以下步驟似乎很簡單,但是我不確定是什么導致了錯誤。 我已經尋找了很長時間,但似乎找不到答案。

class MyClass<T > {
  property: T = 5 // Error Here: Type '5' is not assignable to type T
}

const tester = new MyClass<number>() // OK

const numberValue: number = tester.property // OK
const stringValue: string = tester.property // Error as expected

我認為T可以從“屬性”中推斷為數字。 我覺得過去曾經工作過,但不確定。

帶示例的打字機游樂場


更新資料

這些定義也有相同的錯誤。

class MyClass<T extends number> {
  property: T = 5 // Error Here: Type '5' is not assignable to type T
}

class MyClass<T extends object> {
  property: T = {} // Error Here: Type '{}' is not assignable to type T
}

這應該是行不通的。 無論您在泛型類或方法的定義中編寫的內容如何,​​對於所有可能使用該類或方法的T必須有效。 如果有人執行new MyClass<string>()使得Tstring ,則分配property: T = 5無效。 僅當您使用通用類或方法時才進行推斷。

暫無
暫無

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

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