Skip to content

useShorthandFunctionType

诊断类别:lint/style/useShorthandFunctionType

¥Diagnostic Category: lint/style/useShorthandFunctionType

自从:v1.5.0

¥Since: v1.5.0

来源:

¥Sources:

强制使用函数类型而不是带有调用签名的对象类型。

¥Enforce using function types instead of object type with call signatures.

TypeScript 允许两种常用方式来声明函数类型:

¥TypeScript allows for two common ways to declare a type for a function:

  • 函数类型:() => string

    ¥Function type: () => string

  • 具有签名的对象类型:{ (): string }

    ¥Object type with a signature: { (): string }

通常,如果可能,最好使用函数类型形式,因为它更简洁。

¥The function type form is generally preferred when possible for being more succinct.

此规则建议使用函数类型,而不是具有单个调用签名的接口或对象类型文字。

¥This rule suggests using a function type instead of an interface or object type literal with a single call signature.

¥Examples

¥Invalid

interface Example {
(): string;
}
code-block.ts:2:3 lint/style/useShorthandFunctionType  FIXABLE  ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

Use a function type instead of a call signature.

1 │ interface Example {
> 2 │ (): string;
^^^^^^^^^^^
3 │ }
4 │

Types containing only a call signature can be shortened to a function type.

Safe fix: Alias a function type instead of using an interface with a call signature.

1 - interface·Example·{
2 - ··():·string;
3 - }
1+ type·Example·=·()·=>·string
4 2

function foo(example: { (): number }): number {
return example();
}
code-block.ts:1:25 lint/style/useShorthandFunctionType  FIXABLE  ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

Use a function type instead of a call signature.

> 1 │ function foo(example: { (): number }): number {
^^^^^^^^^^
2 │ return example();
3 │ }

Types containing only a call signature can be shortened to a function type.

Safe fix: Use a function type instead of an object type with a call signature.

1 - function·foo(example:·{·():·number·}):·number·{
1+ function·foo(example:·()·=>·number):·number·{
2 2 return example();
3 3 }

¥Valid

type Example = () => string;
function foo(example: () => number): number {
return bar();
}
// returns the function itself, not the `this` argument.
type ReturnsSelf2 = (arg: string) => ReturnsSelf;
interface Foo {
bar: string;
}
interface Bar extends Foo {
(): void;
}
// multiple call signatures (overloads) is allowed:
interface Overloaded {
(data: string): number;
(id: number): string;
}
// this is equivalent to Overloaded interface.
type Intersection = ((data: string) => number) & ((id: number) => string);

¥Related links