首页 > 解决方案 > 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

解决方案


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


推荐阅读