— TypeScript, Error Handling, Programming — 1 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.
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;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'
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!;
Use the logical OR operator to provide a default value in case the property is undefined
.
1const name1: string = person.name || 'Default Name';
Explicitly assert the variable to be of type string
.
1const name1: string = person.name as string;
Add a conditional check before assignment.
1let name1: string;2if (person.name !== undefined) {3 name1 = person.name;4} else {5 name1 = 'Default Name';6}
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.