【发布时间】:2018-02-26 23:53:55
【问题描述】:
我有一个函数,它接受它的参数并返回一个可以处理这些参数的函数。不幸的是,我根本无法让 TypeScript 对其进行类型检查。这是我的问题的简化示例:
type NoiseMaker<T extends Animal> = (animal: T) => void;
class Dog {
bark() {
console.log('Woof! Woof!');
}
}
class Cat {
meow() {
console.log('Meow')
}
}
type Animal = Dog | Cat;
const bark: NoiseMaker<Dog> = (dog: Dog) => {
dog.bark();
}
function getNoiseMaker<T extends Animal>(animal: T): NoiseMaker<T> {
if (animal instanceof Dog) {
// T is a Dog then, right?
return bark; // ERROR: Type '(dog: Dog) => void' is not assignable to type 'NoiseMaker<T>'.
// Type 'T' is not assignable to type 'Dog'
}
else {
throw new Error("I don't know that kind of animal");
}
}
getNoiseMaker() 返回一个适用于任何给定T 的函数。一旦 TypeScript 确定 T 的类型是或扩展了 Dog,为什么它不允许我返回 bark,这是一个 NoiseMaker<Dog>?
我在这里做错了什么?
【问题讨论】:
标签: typescript