在 Typescript 中实现集合上的泛型函数时,我注意到编译器无法推断两个参数的基本类型。
function union<T>(first: Set<T>, second: Set<T>): Set<T> {
const newSet = new Set<T>(first);
for (const element of second)
newSet.add(element);
return newSet;
}
class Animal { }
class Dog extends Animal {
bark() { console.info('Woof!'); }
}
class Cat extends Animal {
meow() { console.info('Meow!'); }
}
const a = new Set<Dog>();
const b = new Set<Cat>();
然后,如果我调用 union,Typescript 无法推断 T
应该是 Animal
。
const c = union(a, b);
// This results in the error:
// Argument of type 'Set<Cat>' is not assignable to parameter of type 'Set<Dog>'.
// Property 'bark' is missing in type 'Cat' but required in type 'Dog'.ts(2345)
但是如果我明确地使用 T = Animal
调用 union,它就可以正常工作:
const d = union<Animal>(a, b);
我做错了什么?
最佳答案
尝试使用类型联合:
function union<T extends Animal, U extends Animal>(first: Set<T>, second: Set<U>) {
const newSet = new Set<T | U>(first);
for (const element of second)
newSet.add(element);
return newSet;
}
class Animal { }
class Dog extends Animal {
bark() { console.info('Woof!'); }
}
class Cat extends Animal {
meow() { console.info('Meow!'); }
}
const a = new Set<Dog>();
const b = new Set<Cat>();
const c = union(a, b);
添加额外的泛型参数U
有助于TS推断两个Set的类型
关于typescript - 在 Typescript 中推断两个参数的基本类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68376615/