How to fix Type 'unknown' is not assignable to type 'string' in TypeScript

TypeScriptINTERMEDIATEMEDIUMUpdated Dec 11, 2025· 135 views

This TypeScript error occurs when trying to assign an unknown type value directly to a string variable. TypeScript requires type narrowing or assertions to ensure type safety before assignment.

Quick fix

Fixes Type 'unknown' is not assignable to type 'string'

function processValue(value: unknown): string {
  if (typeof value === 'string') {
    return value; // TypeScript knows value is string here
  }
  throw new Error('Value is not a string');
}

// Or assign to variable
let data: unknown = getUserInput();
if (typeof data === 'string') {
  const myString: string = data; // ✓ Works
}
  1. Use typeof type guard for runtime checking
  2. Use type assertion when you are certain of the type
  3. Create custom type guard functions
  4. Use assertion functions for validation
typescript — error
function processValue(value: unknown): string {
if (typeof value === 'string') {
return value; // TypeScript knows value is string here
}
throw new Error('Value is not a string');
}
// Or assign to variable
let data: unknown = getUserInput();
if (typeof data === 'string') {
const myString: string = data; // ✓ Works
}
Type 'unknown' is not assignable to type 'string'

What this error means

This error appears when you attempt to assign a value of type `unknown` to a variable or parameter that expects a `string` type. TypeScript introduced the `unknown` type as a type-safe counterpart to `any`. While `any` allows any operation without checks, `unknown` forces you to verify the type before using it. The `unknown` type represents values whose type is not known at compile time—commonly from user input, API responses, or third-party libraries. TypeScript's type system prevents direct assignment to more specific types to maintain type safety and prevent runtime errors. This is a deliberate design choice that encourages safer code by requiring explicit type checking before narrowing an `unknown` value to a specific type like `string`.

Typical symptoms

  • Compiler error TS2322 when assigning unknown values to string variables
  • Error when returning unknown from functions with string return types
  • Type mismatch errors when passing unknown arguments to string parameters
  • IDE shows red underlines on assignments from API responses or JSON parsing

Common causes

  1. Assigning values from JSON.parse() or catch blocks (which return unknown) directly to string variables
  2. Function parameters typed as unknown being passed to functions expecting strings
  3. API response data not type-checked before assignment
  4. Using values from third-party libraries that return unknown types
  5. Migrating from any to unknown without adding type guards

How to fix "Type 'unknown' is not assignable to type 'string'"

1Use typeof type guard for runtime checking

The safest approach is to check the type at runtime before assignment:

typescript
function processValue(value: unknown): string {
  if (typeof value === 'string') {
    return value; // TypeScript knows value is string here
  }
  throw new Error('Value is not a string');
}

// Or assign to variable
let data: unknown = getUserInput();
if (typeof data === 'string') {
  const myString: string = data; // ✓ Works
}

This pattern ensures type safety while satisfying TypeScript's requirements.

2Use type assertion when you are certain of the type

If you have external knowledge that the value is definitely a string, use a type assertion:

typescript
const response: unknown = await fetch('/api/data').then(r => r.json());
const message = response as string; // Type assertion

// Or with angle bracket syntax (not usable in .tsx files)
const message = <string>response;

Warning: This bypasses TypeScript's safety checks. Use only when you're absolutely certain of the type, otherwise you risk runtime errors.

3Create custom type guard functions

For complex validations, define a type guard function with a type predicate:

typescript
function isString(value: unknown): value is string {
  return typeof value === 'string';
}

const data: unknown = getExternalData();
if (isString(data)) {
  const str: string = data; // ✓ TypeScript knows data is string
  console.log(str.toUpperCase());
}

Type guards are reusable and make your code more maintainable.

4Use assertion functions for validation

Assertion functions throw errors if validation fails, automatically narrowing the type:

typescript
function assertIsString(value: unknown): asserts value is string {
  if (typeof value !== 'string') {
    throw new Error(`Expected string, got ${typeof value}`);
  }
}

const data: unknown = parseInput();
assertIsString(data);
// After this point, TypeScript knows data is a string
const myString: string = data; // ✓ Works

This approach combines runtime validation with type narrowing.

5Handle union types with proper narrowing

When working with unknown from sources like catch blocks, narrow to the expected type or provide defaults:

typescript
async function fetchMessage(): Promise<string> {
  try {
    const response = await fetch('/api/message');
    const data: unknown = await response.json();

    // Validate the shape
    if (typeof data === 'object' && data !== null && 'message' in data) {
      const obj = data as { message: unknown };
      if (typeof obj.message === 'string') {
        return obj.message;
      }
    }
    throw new Error('Invalid response format');
  } catch (error: unknown) {
    // error is unknown in catch blocks
    if (error instanceof Error) {
      return `Error: ${error.message}`;
    }
    return 'Unknown error occurred';
  }
}
6Use validation libraries for complex objects

For API responses and complex data structures, use runtime validation libraries:

typescript
import { z } from 'zod';

const stringSchema = z.string();

function processData(data: unknown): string {
  // parse() throws if validation fails
  return stringSchema.parse(data);
}

// Or with safeParse for error handling
function safeProcessData(data: unknown): string {
  const result = stringSchema.safeParse(data);
  if (result.success) {
    return result.data;
  }
  throw new Error(`Validation failed: ${result.error.message}`);
}

Libraries like Zod, io-ts, or Yup provide robust runtime validation with TypeScript integration.

Advanced notes

Why unknown instead of any?

TypeScript 3.0 introduced unknown as a safer alternative to any. While any opts out of type checking entirely, unknown requires you to prove the type before using it. This catches potential bugs at compile time rather than runtime.

Type narrowing in control flow

TypeScript's control flow analysis tracks type narrowing through your code. Once you verify a type with typeof, instanceof, or a type guard, TypeScript remembers this in subsequent code branches.

Common pattern with catch blocks

Since TypeScript 4.4, catch clause variables have type unknown by default (with useUnknownInCatchVariables enabled). Always check if the error is an Error instance before accessing properties:

typescript
try {
  riskyOperation();
} catch (error: unknown) {
  if (error instanceof Error) {
    console.error(error.message); // Safe
  } else {
    console.error('Unknown error:', String(error));
  }
}

Non-null assertion operator

The ! operator can bypass null/undefined checks but does NOT work for unknown. You must use type guards or assertions.

Frequently asked questions

What does "Type 'unknown' is not assignable to type 'string'" mean?
This error appears when you attempt to assign a value of type unknown to a variable or parameter that expects a string type. TypeScript introduced the unknown type as a type-safe counterpart to any. While any allows any operation without checks, unknown forces you to verify the type before using it.
How do I fix "Type 'unknown' is not assignable to type 'string'"?
This TypeScript error occurs when trying to assign an unknown type value directly to a string variable. TypeScript requires type narrowing or assertions to ensure type safety before assignment.
What causes "Type 'unknown' is not assignable to type 'string'"?
Assigning values from JSON.parse() or catch blocks (which return unknown) directly to string variables Function parameters typed as unknown being passed to functions expecting strings API response data not type-checked before assignment
Is the "Type 'unknown' is not assignable to type 'string'" error serious?
It is a medium-severity error — more of a blocker than a risk. The steps above resolve it.

Official resources & further reading