typescript/no-misused-spread 正确性
它做了什么
此规则禁止在不适用或可能导致运行时错误的位置使用展开语法。
为什么这是个问题?
展开运算符可能被误用,这些误用可能并不明显,但却会导致运行时错误或意外行为。此规则有助于捕获常见的误用情况。
示例
以下为 错误 用法的示例:
ts
// 在数组中展开非可迭代值
const num = 42;
const arr = [...num]; // 运行时错误:num 不是可迭代对象
// 在数组中展开 Promise
const promise = Promise.resolve([1, 2, 3]);
const arr2 = [...promise]; // 运行时错误:Promise 不是可迭代对象
// 在对象字面量中展开非对象
const str = "hello";
const obj = { ...str }; // 会创建 { '0': 'h', '1': 'e', ... },这可能不符合预期以下为 正确 用法的示例:
ts
// 展开数组
const arr1 = [1, 2, 3];
const arr2 = [...arr1];
// 展开对象
const obj1 = { a: 1, b: 2 };
const obj2 = { ...obj1 };
// 展开已解决的 Promise
const promise = Promise.resolve([1, 2, 3]);
const arr3 = [...(await promise)];
// 如有必要,使用 Array.from 处理非可迭代对象
const str = "hello";
const arr4 = Array.from(str); // ['h', 'e', 'l', 'l', 'o']配置
此规则接受一个配置对象,包含以下属性:
allow
type: array
default: []
一个允许展开的类型或值规范数组,即使它们通常会被标记为误用。
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-misused-spread": "error"
}
}bash
oxlint --type-aware --deny typescript/no-misused-spread