Skip to content
DeveloperMemos

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.

Example

1interface Person {
2 name?: string;
3}
4
5function getPerson(): Person {
6 return { name: "John" };
7}
8
9const person: Person = getPerson();
10const name1: string = person.name; // 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 = person.name!;

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 = person.name || 'Default Name';

3. Type Assertion

Explicitly assert the variable to be of type string.

1const name1: string = person.name as string;

4. Conditional Check

Add a conditional check before assignment.

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

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.