typescript/no-deprecated 严谨
它的作用
禁止使用标记为 @deprecated 的代码。
为什么这是不好的?
JSDoc 的 @deprecated 标签可用于标记某段代码已被弃用。最好避免使用被标记为弃用的代码。此规则会报告所有对被标记为 @deprecated 的代码的引用。
TypeScript 识别 @deprecated 标签,允许编辑器以视觉方式标注弃用代码——通常以删除线形式呈现。然而,TypeScript 本身不会为弃用的代码报告类型错误。
示例
此规则的错误代码示例:
ts
/** @deprecated 改用 apiV2。 */
declare function apiV1(): Promise<string>;
declare function apiV2(): Promise<string>;
await apiV1(); // 使用弃用函数
import { parse } from "node:url";
// 'parse' 已被弃用。请改用 WHATWG URL API。
const url = parse("/foo");此规则的正确代码示例:
ts
/** @deprecated 改用 apiV2。 */
declare function apiV1(): Promise<string>;
declare function apiV2(): Promise<string>;
await apiV2(); // 使用非弃用函数
// 现代 Node.js API,使用 `new URL()`
const url2 = new URL("/foo", "http://www.example.com");配置
此规则接受一个配置对象,包含以下属性:
allow
type: array
default: []
一个数组,用于指定即使被弃用也允许使用的类型或值标识符。可使用此选项来允许你有意继续使用的特定弃用的 API。
allow[n]
type: string
用于匹配特定声明的类型或值标识符
支持四种类型的标识符:
- 字符串标识符(已弃用):按名称进行通用匹配
json
"Promise"- 文件标识符:匹配在本地文件中声明的类型/值
json
{ "from": "file", "name": "MyType" }
{ "from": "file", "name": ["Type1", "Type2"] }
{ "from": "file", "name": "MyType", "path": "./types.ts" }- 库标识符:匹配 TypeScript 内置库类型
json
{ "from": "lib", "name": "Promise" }
{ "from": "lib", "name": ["Promise", "PromiseLike"] }- 包标识符:匹配 npm 包中的类型/值
json
{ "from": "package", "name": "Observable", "package": "rxjs" }
{ "from": "package", "name": ["Observable", "Subject"], "package": "rxjs" }如何使用
要通过配置文件或 CLI 启用此规则,可以使用:
json
{
"rules": {
"typescript/no-deprecated": "error"
}
}bash
oxlint --type-aware --deny typescript/no-deprecated