no-unsafe-return
Disallow returning a value with type
any
from a function.
该规则需要 类型信息 才能运行,但这会带来性能方面的权衡。
TypeScript 中的 any
类型是来自类型系统的危险 "应急方案"。使用 any
会禁用许多类型检查规则,通常最好只作为最后的手段或在原型代码时使用。
¥The any
type in TypeScript is a dangerous "escape hatch" from the type system.
Using any
disables many type checking rules and is generally best used only as a last resort or when prototyping code.
尽管你有最好的意图,但 any
类型有时会泄漏到你的代码库中。从函数返回 any
类型的值会在你的代码库中产生潜在的类型安全漏洞和错误来源。
¥Despite your best intentions, the any
type can sometimes leak into your codebase.
Returning an any
-typed value from a function creates a potential type safety hole and source of bugs in your codebase.
此规则不允许从函数返回 any
或 any[]
,并从异步函数返回 Promise<any>
。
¥This rule disallows returning any
or any[]
from a function and returning Promise<any>
from an async function.
此规则还比较泛型类型参数类型,以确保你不会将通用位置中的不安全 any
返回给期望特定类型的函数。例如,如果从声明为返回 Set<string>
的函数返回 Set<any>
,则会出错。
¥This rule also compares generic type argument types to ensure you don't return an unsafe any
in a generic position to a function that's expecting a specific type.
For example, it will error if you return Set<any>
from a function declared as returning Set<string>
.
- Flat Config
- Legacy Config
export default tseslint.config({
rules: {
"@typescript-eslint/no-unsafe-return": "error"
}
});
module.exports = {
"rules": {
"@typescript-eslint/no-unsafe-return": "error"
}
};
在线运行试试这个规则 ↗
示例
¥Examples
- ❌ Incorrect
- ✅ Correct
function foo1() {
return 1 as any;
}
function foo2() {
return Object.create(null);
}
const foo3 = () => {
return 1 as any;
};
const foo4 = () => Object.create(null);
function foo5() {
return [] as any[];
}
function foo6() {
return [] as Array<any>;
}
function foo7() {
return [] as readonly any[];
}
function foo8() {
return [] as Readonly<any[]>;
}
const foo9 = () => {
return [] as any[];
};
const foo10 = () => [] as any[];
const foo11 = (): string[] => [1, 2, 3] as any[];
async function foo13() {
return Promise.resolve({} as any);
}
// generic position examples
function assignability1(): Set<string> {
return new Set<any>([1]);
}
type TAssign = () => Set<string>;
const assignability2: TAssign = () => new Set<any>([true]);
Open in Playgroundfunction foo1() {
return 1;
}
function foo2() {
return Object.create(null) as Record<string, unknown>;
}
const foo3 = () => [];
const foo4 = () => ['a'];
async function foo5() {
return Promise.resolve(1);
}
function assignability1(): Set<string> {
return new Set<string>(['foo']);
}
type TAssign = () => Set<string>;
const assignability2: TAssign = () => new Set(['foo']);
Open in Playground有些情况下规则允许将 any
返回给 unknown
。
¥There are cases where the rule allows to return any
to unknown
.
允许返回 any
到 unknown
的示例:
¥Examples of any
to unknown
return that are allowed:
function foo1(): unknown {
return JSON.parse(singleObjString); // Return type for JSON.parse is any.
}
function foo2(): unknown[] {
return [] as any[];
}
Open in Playground