interface ISave{
save(path: string, computer: Computer): void;
}
class SaveComputerToFile implements ISave{
public save(): void{
console.log(("saving in file"));
}
}
为什么打字稿不显示错误,因为在
SaveComputerToFile
类中,save 方法没有参数,尽管它应该有?
我尝试在
strictFunctionTypes
文件中启用 tsconfig.json
并重新启动程序,但这也没有帮助
TypeScript 根据参数类型和计数检查方法签名是否匹配。如果您在 SaveComputerToFile 中定义不带参数的 save 方法,TypeScript 在某些情况下可能会允许它,但它不会真正实现接口。
要解决此问题,请确保您的保存方法如下所示:
class SaveComputerToFile implements ISave {
public save(path: string, computer: Computer): void {
console.log("saving in file");
}
}
如果您想要更严格的检查,请在 tsconfig.json 中启用严格模式:
{
"compilerOptions": {
"strict": true,
"strictFunctionTypes": true,
// other options
}
}
通过此设置,如果方法与接口不匹配,TypeScript 应该标记错误。如果您仍然没有看到错误,请检查您的 TypeScript 文件是否正确编译。