typescript/prefer-function-type 风格
它做了什么
强制使用函数类型,而不是仅包含调用签名的接口。
为什么这是不好的?
TypeScript 允许两种常见方式来声明函数类型:
- 函数类型:
() => string - 带有签名的对象类型:
{ (): string }
当可能时,通常更推荐使用函数类型形式,因为它更加简洁和易读。仅包含调用签名的接口会增加不必要的冗余,却没有提供额外的功能。
示例
此规则的 错误 示例:
typescript
interface Example {
(): string;
}
function foo(example: { (): number }): number {
return example();
}
interface ReturnsSelf {
(arg: string): this;
}此规则的 正确 示例:
typescript
type Example = () => string;
function foo(example: () => number): number {
return example();
}
// 返回函数本身,而不是 `this` 参数
type ReturnsSelf = (arg: string) => ReturnsSelf;
// 多个属性是允许的
function foo(bar: { (): string; baz: number }): string {
return bar();
}
// 多个调用签名(重载)是允许的
interface Overloaded {
(data: string): number;
(id: number): string;
}
// 这等价于 Overloaded 接口。
type Intersection = ((data: string) => number) & ((id: number) => string);如何使用
要通过配置文件或 CLI 启用此规则,可以使用:
json
{
"rules": {
"typescript/prefer-function-type": "error"
}
}bash
oxlint --deny typescript/prefer-function-type