typescript/explicit-module-boundary-types 限制
它做了什么
要求在导出的函数和类的公共类方法上显式声明返回值类型和参数类型。
为什么这是个问题?
为函数返回值和参数添加显式的类型,可以让调用代码清晰地了解模块边界的输入和输出。为这些类型添加显式类型注解有助于提高代码可读性。同时,它还能提升大型代码库中 TypeScript 类型检查的性能。
示例
此规则的错误代码示例:
ts
// 应表明不返回任何值(void)
export function test() {
return;
}
// 应表明返回的是字符串
export var arrowFn = () => "test";
// 所有参数都应进行类型标注
export var arrowFn = (arg): string => `test ${arg}`;
export var arrowFn = (arg: any): string => `test ${arg}`;
export class Test {
// 应表明不返回任何值(void)
method() {
return;
}
}此规则的正确代码示例:
ts
// 没有返回值的函数(void)
export function test(): void {
return;
}
// 返回值类型为字符串
export var arrowFn = (): string => "test";
// 所有参数都应进行类型标注
export var arrowFn = (arg: string): string => `test ${arg}`;
export var arrowFn = (arg: unknown): string => `test ${arg}`;
export class Test {
// 无返回值的类方法(void)
method(): void {
return;
}
}
// 该函数不适用,因为它不是导出的函数。
function test() {
return;
}配置
此规则接受一个配置对象,包含以下属性:
allowArgumentsExplicitlyTypedAsAny
type: boolean
default: false
是否忽略被显式标注为 any 的参数。
allowDirectConstAssertionInArrowFunctions
type: boolean
default: true
是否忽略仅返回 as const 类型断言的无主体箭头函数上的返回类型注解。你仍然需要对函数的参数进行类型标注。
allowHigherOrderFunctions
type: boolean
default: true
是否忽略立即返回另一个函数表达式的函数的返回类型注解。你仍然需要对函数的参数进行类型标注。
allowOverloadFunctions
type: boolean
default: false
是否忽略具有重载签名的函数的返回类型注解。
allowTypedFunctionExpressions
type: boolean
default: true
是否忽略函数表达式变量上的类型注解。
allowedNames
type: string[]
default: []
一个函数/方法名称数组,这些名称的参数或返回值将不会被检查。
如何使用
通过配置文件或 CLI 启用此规则,可以使用:
json
{
"rules": {
"typescript/explicit-module-boundary-types": "error"
}
}bash
oxlint --deny typescript/explicit-module-boundary-types