我有一个简单的界面:
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:
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[]'我根据我在网上看到的例子使用了泛型/扩展,所以不知道我在这里误解了什么。
发布于 2022-09-18 14:04:14
我理解您为什么使用T extends T[],因为当您不使用这个错误时:
输入'T‘不能指定为’T[]‘。(2416) input.tsx(11,11):这个类型参数可能需要一个
extends T[]约束。
在这种情况下,这个错误是误导的,但是如果我们仔细考虑我们想要什么,我们就能得到解决方案。
您希望isMatch采用T[]类型。然而,Cat只使用T。请记住,isMatch是由接口Animal定义的,而在接口中,它采用T (在接口中)。如果我们想要这些类型匹配,我们只需要让Animal采取T[]!
class Cat<T> implements Animal<T[]> {就是这样。
https://stackoverflow.com/questions/73763347
复制相似问题