Skip to content

Resolving TypeScript Error: 'string | undefined' is not assignable to 'string'

TypeScript, Error Handling, Programming1 min read

In TypeScript, you might encounter the error "Type 'string | undefined' is not assignable to type 'string'" when working with optional properties in interfaces. This article explains how to resolve this error effectively.

Understanding the Error

When you define an optional property in an interface, TypeScript treats this property as string | undefined. However, when you try to assign this property to a variable of type string, TypeScript throws an error because the types do not match exactly.


1interface Person {
2 name?: string;
5function getPerson(): Person {
6 return { name: "John" };
9const person: Person = getPerson();
10const name1: string =; // Error: 'string | undefined' is not assignable to 'string'

Solutions to Resolve the Error

1. Non-null Assertion Operator (!)

You can use the non-null assertion operator to tell TypeScript that the value will not be null or undefined.

1const name1: string =!;

2. Using the Logical OR Operator (||)

Use the logical OR operator to provide a default value in case the property is undefined.

1const name1: string = || 'Default Name';

3. Type Assertion

Explicitly assert the variable to be of type string.

1const name1: string = as string;

4. Conditional Check

Add a conditional check before assignment.

1let name1: string;
2if ( !== undefined) {
3 name1 =;
4} else {
5 name1 = 'Default Name';

In Closing

The TypeScript error "Type 'string | undefined' is not assignable to type 'string'" is common when dealing with optional properties. By using one of the above methods, you can resolve this error while ensuring that your code remains type-safe and ROBUST.