Fix TypeScript 'any' Spreading: Validate Unknown Values Safely
Troubleshoot TypeScript spread errors with unknown values, object narrowing, safe merge patterns, and typed generics.
TechSilo
Technology writer & developer
Spreading a value from an API or untyped library can hide bugs. The correct fix depends on whether you're spreading an object ({ ...value }) or iterable elements ([...value]).
Why spreading untrusted values is risky
function mergeUnsafe(input: any) {
return { enabled: true, ...input };
}TypeScript's any disables useful checks, so this may compile while accepting a string, array, or unexpected object shape. unknown is safer: it forces you to inspect the input before using it.
Fix object spreading with narrowing
function isRecord(value: unknown): value is Record<string, unknown> {
return typeof value === 'object' &&
value !== null &&
!Array.isArray(value);
}
function mergeOptions(value: unknown) {
return {
enabled: true,
...(isRecord(value) ? value : {}),
};
}
console.log(mergeOptions({ retries: 2 }));The guard makes the spread operand a non-null object. You can narrow further when individual properties must have known types.
Validate a specific API payload
type Preferences = {
theme: 'light' | 'dark';
notifications: boolean;
};
function parsePreferences(input: unknown): Preferences {
if (!isRecord(input)) throw new Error('Expected an object');
const theme = input.theme;
const notifications = input.notifications;
if ((theme !== 'light' && theme !== 'dark') ||
typeof notifications !== 'boolean') {
throw new Error('Invalid preferences payload');
}
return { theme, notifications };
}A type assertion such as input as Preferences does not validate anything at runtime. Use a validation library if your schema is large.
Array spreading is different
function appendNumbers(value: unknown): number[] {
if (!Array.isArray(value) || !value.every(x => typeof x === 'number')) {
throw new Error('Expected an array of numbers');
}
return [0, ...value];
}A generic function can preserve known element types:
function concatItems<T>(first: readonly T[], second: readonly T[]): T[] {
return [...first, ...second];
}Common compiler messages
- "Spread types may only be created from object types": check the operand; union members such as null or primitives may need narrowing.
- "Type X must have a '[Symbol.iterator]()' method": the value is not known to be iterable; narrow it to an array or other iterable.
- "Argument of type 'unknown' is not assignable": validate before assigning or spreading.
A safer debugging sequence
Start with the type at the data boundary, change unnecessary any to unknown, add a runtime guard, and only then perform the spread. Avoid solving type errors with as any because that bypasses the protection you needed. Learn the surrounding JavaScript behavior with TechSilo's [AI Code Explainer](/tools/ai-code-explainer).
Want to put this into practice?
Explore TechSilo's free developer tools for practical utilities you can use directly in your browser.
Related blog posts
Console.log Alternatives for Efficient JavaScript Debugging
Use browser breakpoints, console.table, console.trace, timing APIs, and structured logs to debug without flooding production consoles.
Read postTroubleshooting CORS Errors in Production: Step-by-Step Guide
Diagnose missing CORS headers, blocked OPTIONS preflights, proxy errors, and credential mismatches without weakening API security.
Read postFix Next.js Hydration Mismatches: Causes and Safe Solutions
Troubleshoot React hydration errors in Next.js from dates, browser-only APIs, random output, incorrect markup, and third-party libraries.
Read postTypeScript Utility Types Cheat Sheet: Pick, Omit, Partial and More
Practical examples of TypeScript Partial, Required, Pick, Omit, Record, ReturnType, Awaited, Extract, and Exclude.
Read postUnderstanding CSS Specificity: How the Cascade Picks Styles
Understand CSS specificity, source order, cascade layers, :is(), :where(), and practical ways to debug overriding styles.
Read post