【发布时间】:2016-10-18 01:19:20
【问题描述】:
这个 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 中,一元函数是一元函数。传递的额外参数被简单地忽略。这在事件处理中很常见。所以你的函数是正确的签名。
-
@FengyangWang:我不反对,只是要说 TypeScript 做了很多事情,而这些事情并不是仅仅作为 JavaScript 发出的,因此可以强制执行类型安全。我只是好奇我是否能找到一种方法来强制执行这种类型安全。