typescript - TypeScript:为什么在实现接口时函数参数不被视为强制性的?
问题描述
我最近注意到我能够从接口实现一个函数并删除参数并且效果很好。我在下面有一些示例代码来演示。难道不应该强制实现接口的类也实现正确数量和类型的参数吗?
打字稿版本:4.1.3
示例界面:
interface IVehicle {
turn(direction: string, degree: number): void;
turnHeadlights(toggle: boolean): void;
}
示例一:
class Vehicle implements IVehicle {
turn(direction: string): void {
throw new Error("Method not implemented.");
}
turnHeadlights(toggle: boolean): void {
throw new Error("Method not implemented.");
}
}
示例二:
class VehicleStub implements IVehicle {
turn(): void {
throw new Error("Method not implemented.");
}
turnHeadlights(): void {
throw new Error("Method not implemented.");
}
}
解决方案
Typescript 是故意这样设计的。函数上的类型是为了确保所有正确的数据都传递到函数中。它不会强制函数对这些值进行实际操作。
javascript 代码忽略未使用的参数实际上很常见。比如map等数组函数:
const array1 = [1, 2, 3];
const array2 = array1.map(value => value * 2); // creates [2, 4, 6]
但是您传入的函数实际上接收 3 个参数,而不是 1 个。如果 typescript 强制您将它们全部列出,您将不得不将其重写为:
const array1 = [1, 2, 3];
const array2 = array1.map((value, index, arr) => value * 2);
强迫你声明你不会使用的变量几乎没有什么好处,所以他们设计了打字稿来不强制这样做。只要您的函数与传入的数据兼容,它就会允许它。
有关更多信息,请参阅此页面:https ://www.typescriptlang.org/docs/handbook/type-compatibility.html#comparing-two-functions
推荐阅读
- c++ - UVA 10077 - 为什么是二进制搜索?
- java - SQLite 查询的空引用
- kotlin - 如何创建类型的 lambda ((KeyboardEvent) -> dynamic)?在科特林
- jquery - Laravel - 如何根据条件为动态输入字段指定行
- azure-devops - 如何将 TestNG 或范围报告与 Azure devops 集成?
- gradle - 如何在具有 android、iOS 和不受支持的目标(如 mingwX64)的 kotlin 多平台项目中设置 sqldelight?
- java - 压缩视频质量并上传到 firebase 无法压缩 mp4 视频的大小
- python - 在 Pandas Dataframe 上使用 groupby 按一列重新排列,最大值仅为另一列
- php - php 中的 Google 健身 API
- android - 无法加载或替换片段的 XML 但在新片段中运行代码?