Skip to content
Back to all posts
Technology

Fix TypeScript 'any' Spreading: Validate Unknown Values Safely

Troubleshoot TypeScript spread errors with unknown values, object narrowing, safe merge patterns, and typed generics.

3 min read

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

typescript
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

typescript
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

typescript
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

typescript
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:

typescript
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