Argument type ‘undefined’ is not assignable parameter of type – How to fix it?

Argument type ‘undefined’ is not assignable parameter of type

The error “Argument type ‘undefined’ is not assignable parameter of type” happens very commonly in Typescript, but it is also easy to solve. Let’s go into detail now.

The reason of the error “Argument type ‘undefined’ is not assignable parameter of type”

The error happens when you try to pass in a parameter without setting a type. When Typescript does not know the type of argument, it will try to infer it. However, if you are using not a valid type or something not valid in Typescript, Typescript will set it to ‘undefined’ then the error happens.

Example of how the error happens:

const welcome = (greet: string) => {
    console.log(greet);
};

welcome(undefined);  

The error:

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

The error happens because I passed in ‘undefined’ parameter instead of a ‘string’ parameter.

The solution for this error

Check your logic

Of course, the simple solution is that you should define the correct type of argument you want to pass into the parameter. Obviously here, I should pass in a ‘string’ instead of an ‘undefined’ type.

Example:

const welcome = (greet: string) => {
    console.log(greet);
};

welcome("Hello From Learn Share IT");

Output:

"Hello From Learn Share IT"

Then the error has gone away.

Use ‘any’ type

You can set the type for the parameter as ‘any’ type. Because it can get any argument you pass in. It is simple to solve the error in that way, but I do not recommend you do it. Because if you set too much of ‘any’ type, you will return to Javascript with dynamic type, and the power of Typescript is also lost.

Example:

const error = undefined;

const welcome = (greet: any) => {
    console.log(greet);
};

welcome(error);

Output:

undefined

Here with ‘any’ type, I can even pass in ‘undefined’ type.

Use type guard

You can also check the argument type before passing in the parameter or make some logic to check the type.

Example:

const error = undefined;

const greet = (str: string | undefined) => {
    if (str) {
        console.log(str);
    } else {
        console.log("Invalid input");
    }
};

greet("Hello From LearnShare IT");
greet(error);

Here I create a greet() function that can get either ‘string’ or ‘undefined’ type and make an if...else statement to check if the value is valid.

Output:

"Hello From Learn Share IT"
"Invalid input"

Summary

In this tutorial, I’ve showed you how to solve the error “Argument type ‘undefined’ is not assignable parameter of type”. You can define the correct type of argument you want to pass into the parameter, set ‘any’ type or make a type guard for your parameters. I hope this article is helpful for you, thank you for reading!

Maybe you are interested:

Leave a Reply

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