How To Solve “Argument of type ‘string or undefined’ is not assignable to parameter of type string” in TypeScript

The data type of a variable can have the value undefined. When passing this data to a function that wants to receive a string value, an error “Argument of type ‘string or undefined’ is not assignable to parameter of type string” appears. To solve this error, we need to tell TypeScript exactly what data type we want to use. Let’s find out in this article.

The cause of the error “Argument of type ‘string or undefined’ is not assignable to parameter of type string”

The error occurs when we pass the parameter to the function because the function needs a string value, but the input value can be undefined or string type, so the error occurs.

Error Example:

function GetName(name: string) {
    return name;
}

// The variable newName can have a value of "John" but it can also have a value of undefined
const newName = Math.random() > 0.3 ? "John" : undefined;

// The GetName function expects to receive string data type.
GetName(newName);

Output:

Argument of type 'string | undefined' is not assignable to parameter of type 'string'.

In the above example, we create a function GetName whose argument is a string name. To illustrate this example, we create a variable newName that can take a name or an undefined type depending on the result returned by the Math.random() function. Because variable newName can take one in two values, when passed to the GetName function, an error will be generated because the GetName function only accepts string values.

Solution for the error “Argument of type ‘string or undefined’ is not assignable to parameter of type string”

To solve this error we have to make TypeScript know about the data type we want to work with, there are many ways, for example, using the non-null assertion, type assertion.

Use Non-null Assertion Operator

By using ‘!‘ after each expression, we tell TypeScript that we want to remove null and undefined types from a data type.

Example:

function GetName(name: string) {
    return name;
}
const newName = Math.random() > 0.5 ? "John" : undefined;

// Adding '!' to remove undefined
console.log(GetName(newName!));

Output:

John

Use Type Assertions

To let TypeScript understand the data type we want to use, we will use Type Assertions to specify the type we want.

Example:

function GetName(name: string) {
    return name;
}
const newName = Math.random() > 0.5 ? "John" : undefined;

// Use Type Assertions to specify the type
console.log(GetName(newName as string));

Output:

John

Summary

Through this article, we have solved the error “Argument of type ‘string or undefined’ is not assignable to parameter of type string“. To avoid errors, you need to pay attention to the data type before passing it to the function. Hope you get the error resolved soon.

Leave a Reply

Your email address will not be published. Required fields are marked *