这个 TypeScript 编译得很好:
abstract class Animal {
/*
Any extension of Animal MUST have a function which returns
another function that has exactly the signature (string): void
*/
abstract getPlayBehavior(): (toy: string) => void;
}
class Cat extends Animal {
/*
Clearly does not have a function which returns a function
that has the correct signature. This function returns a function with
the signature (void) : void
*/
getPlayBehavior() {
return () => {
console.log(`Play with toy_var_would_go_here!`);
};
}
}
class Program {
static main() {
let cat: Animal = new Cat();
cat.getPlayBehavior()("Toy");
}
}
Program.main();
我期待一个错误,因为 Cat 类绝对没有正确实现抽象 Animal 类。我希望 Cat 类必须有一个函数,该函数返回另一个具有抽象 Animal 类中指定的确切签名的函数。
运行代码,我得到:
> node index.js
> Play with toy_var_would_go_here!
我可以做些什么来确保编译器强制执行这种策略?
最佳答案
您不会收到错误,因为在 javascript/typescript 中,如果您不想使用参数,只要不存在矛盾,就不会被迫声明它们。
例如 Array.forEach 的签名是:
forEach(callbackfn: (value: T, index: number, array: T[]) => void, thisArg?: any): void;
但这会编译得很好:
let a = [1, 2, 3];
a.forEach(item => console.log(item));
这是一件好事,如果我必须拥有所有参数,即使我不使用它们,那也会很可怕。
这里也是如此:
type MyFn = (s: string) => void;
let fn: MyFn = () => console.log("hey");
如果我不需要使用字符串参数,那么我可以忽略它,或者我什至可以这样做:
let fn: MyFn = () => console.log(arguments);
如果您将 Cat.getPlayBehavior
中返回的函数签名更改为与 Animal
中的定义相矛盾的内容,则会收到错误消息:
class Cat extends Animal {
getPlayBehavior() {
return (n: number) => {
console.log(`Play with toy_var_would_go_here!`);
};
}
}
错误:
Class 'Cat' incorrectly extends base class 'Animal'.
Types of property 'getPlayBehavior' are incompatible.
Type '() => (n: number) => void' is not assignable to type '() => (toy: string) => void'.
Type '(n: number) => void' is not assignable to type '(toy: string) => void'.
Types of parameters 'n' and 'toy' are incompatible.
Type 'string' is not assignable to type 'number'.
关于typescript - 如何获得 TypeScript 中返回函数的类型安全?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40098030/