typescript/no-misused-spread Correctness
What it does
This rule disallows spreading syntax in places where it doesn't make sense or could cause runtime errors.
Why is this bad?
The spread operator can be misused in ways that might not be immediately obvious but can cause runtime errors or unexpected behavior. This rule helps catch common misuses.
Examples
Examples of incorrect code for this rule:
ts
// Spreading a non-iterable value in an array
const num = 42;
const arr = [...num]; // Runtime error: num is not iterable
// Spreading a Promise in an array
const promise = Promise.resolve([1, 2, 3]);
const arr2 = [...promise]; // Runtime error: Promise is not iterable
// Spreading non-object in object literal
const str = "hello";
const obj = { ...str }; // Creates { '0': 'h', '1': 'e', ... } which might be unexpectedExamples of correct code for this rule:
ts
// Spreading arrays
const arr1 = [1, 2, 3];
const arr2 = [...arr1];
// Spreading objects
const obj1 = { a: 1, b: 2 };
const obj2 = { ...obj1 };
// Spreading resolved Promise
const promise = Promise.resolve([1, 2, 3]);
const arr3 = [...(await promise)];
// Using Array.from for non-iterables if needed
const str = "hello";
const arr4 = Array.from(str); // ['h', 'e', 'l', 'l', 'o']Configuration
This rule accepts a configuration object with the following properties:
allow
type: array
default: []
An array of type or value specifiers that are allowed to be spread even if they would normally be flagged as misused.
allow[n]
type: string
Type or value specifier for matching specific declarations
Supports four types of specifiers:
- String specifier (deprecated): Universal match by name
json
"Promise"- File specifier: Match types/values declared in local files
json
{ "from": "file", "name": "MyType" }
{ "from": "file", "name": ["Type1", "Type2"] }
{ "from": "file", "name": "MyType", "path": "./types.ts" }- Lib specifier: Match TypeScript built-in lib types
json
{ "from": "lib", "name": "Promise" }
{ "from": "lib", "name": ["Promise", "PromiseLike"] }- Package specifier: Match types/values from npm packages
json
{ "from": "package", "name": "Observable", "package": "rxjs" }
{ "from": "package", "name": ["Observable", "Subject"], "package": "rxjs" }How to use
To enable this rule using the config file or in the CLI, you can use:
json
{
"rules": {
"typescript/no-misused-spread": "error"
}
}bash
oxlint --type-aware --deny typescript/no-misused-spread