我有一個簡單的界面:
interface Animal<T> {
isMatch: (value: T) => boolean
}
使用這些實作:
class Dog implements Animal<string> {
isMatch(input: string): boolean {
// do something with string
}
}
和
class Cat<T extends T[]> implements Animal<T> {
isMatch(input: T[]): boolean {
// do something with list
}
}
我可以Dog毫無問題地實體化:
const dog = new Dog("pug")
但是,我不能Cat用以下任何一種來實體化 a:
const siamese = new Cat<string>(...) // Type 'string' does not satisfy the constraint 'string[]'
const persian = new Cat<string[]>(...) // Type 'string[]' does not satisfy the constraint 'string[][]'
const sphynx = new Cat(["birman"]) // Type 'string' does not satisfy the constraint 'string[]'
我根據我在網上看到的示例使用了泛型/擴展,所以不確定我在這里誤解了什么。
uj5u.com熱心網友回復:
我理解你為什么使用T extends T[],因為當你不這樣做時會出現這個錯誤:
型別“T”不可分配給型別“T[]”。(2416)
input.tsx(11, 11):這個型別引數可能需要一個
extends T[]約束。
這個錯誤在這種情況下是誤導性的,但是如果我們想清楚我們想要什么,我們就可以得到解決方案。
你要isMatch取型別T[]。但是,Cat只需要T. 請記住,它isMatch是由 interface 定義的Animal,并且在 interface 中,它需要T(在 interface 中)。如果我們希望這些型別匹配,我們只需要 make Animaltake T[]!
class Cat<T> implements Animal<T[]> {
就是這樣。
操場
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/510467.html
標籤:打字稿仿制药类型界面
上一篇:兩個類的泛型:.NET6
