Type 'string or null' is not assignable to type string (TS)

avatar
Borislav Hadzhiev

Last updated: Feb 28, 2024
10 min

banner

# Table of Contents

  1. Type 'string or null' is not assignable to type string (TS)
  2. Argument type 'string or null' not assignable to parameter of type string
  3. Type 'null' is not assignable to type in TypeScript

# Type 'string or null' is not assignable to type string (TS)

The "Type 'string | null' is not assignable to type string" error occurs when a possibly null value is assigned to something that expects a string.

To solve the error, use a non-null assertion or a type guard to verify the value is a string before the assignment.

Here is an example of how the error occurs.

index.ts
interface Employee { id: number; name: string | null; } const emp: Employee = { id: 1, name: 'Bobby Hadz', }; // โ›”๏ธ Error: Type 'string | null' is // not assignable to type 'string'. // Type 'null' is not assignable to type 'string'.ts(2322) const name: string = emp.name;

type null is not assignable to type string

The name property in the Employee interface has a type of string | null.

The name variable is typed as a string, so it only expects to get assigned a value that is a string.

TypeScript is telling us that the emp.name property might have a value of null, which is not compatible with the type of the name variable, which only expects a string.

# Using the non-null assertion operator to solve the error

One way to solve the error is to use the non-null assertion (!) operator.

index.ts
interface Employee { id: number; name: string | null; } const emp: Employee = { id: 1, name: 'Bobby Hadz', }; // eslint-disable-next-line @typescript-eslint/no-non-null-assertion const name: string = emp.name!; // ๐Ÿ‘ˆ๏ธ non-null assertion

using non null assertion operator to solve the error

The code for this article is available on GitHub

The exclamation mark is the non-null assertion operator in TypeScript.

It removes null and undefined from a type without doing any explicit type-checking.

When you use this approach, you basically tell TypeScript that this value will never be null or undefined.

# Using a type assertion to solve the error

This is very similar to a type assertion and should only be used when you're absolutely sure that the value is of the expected type.

index.ts
interface Employee { id: number; name: string | null; } const emp: Employee = { id: 1, name: 'Bobby Hadz', }; const name: string = emp.name as string; // ๐Ÿ‘ˆ๏ธ type assertion console.log(name); // ๐Ÿ‘‰๏ธ "Bobby Hadz"

using type assertion to solve the error

The code for this article is available on GitHub
Type assertions are used when we have information about the type of a value that TypeScript can't know about.

We effectively tell TypeScript that emp.name will be a string and not to worry about it.

# Using a type guard to solve the error

An alternative and much better approach is to use a type guard.

index.ts
interface Employee { id: number; name: string | null; } const emp: Employee = { id: 1, name: 'Bobby Hadz', }; const name: string = emp.name !== null ? emp.name : ''; console.log(name); // ๐Ÿ‘‰๏ธ "Bobby Hadz"

using type guard to solve the error

The ternary operator is very similar to an if/else statement.

If the expression to the left of the question mark is truthy, the operator returns the value to the left of the colon, otherwise, the value to the right of the colon is returned.

If the property is not equal to null, it gets assigned to the name variable, otherwise, we use an empty string as a fallback.

This way we can be sure that the name variable will always get assigned a string, even if emp.name is null.

# Using the nullish coalescing operator (??) to solve the error

You could also use the nullish coalescing operator (??) to solve the error.

index.ts
interface Employee { id: number; name: string | null; } const emp: Employee = { id: 1, name: 'Bobby Hadz', }; const name: string = emp.name ?? ''; console.log(name); // ๐Ÿ‘‰๏ธ "Bobby Hadz"

using nullish coalescing operator to solve the error

The code for this article is available on GitHub
The nullish coalescing operator (??) enables us to specify a fallback for when a value is null or undefined.

So, if emp.name is null or undefined, we set the name variable to an empty string.

# Using the logical OR (||) operator to solve the error

You can also use the logical OR (||) operator in a similar way.

index.ts
interface Employee { id: number; name: string | null; } const emp: Employee = { id: 1, name: 'Bobby Hadz', }; const name: string = emp.name || ''; console.log(name); // ๐Ÿ‘‰๏ธ "Bobby Hadz"

using logical or operator to solve the error

The logical OR (||) operator returns the value to the right if the value to the left is falsy.

This is different than the nullish coalescing operator (??), because nullish coalescing only checks for null and undefined.

The logical OR (||) operator would return the value to the right if the value to the left is any of the following: null, undefined, false, 0, "" (empty string), NaN (not a number).

# Using an if statement to solve the error

Even a simple if statement that serves as a type guard can be used to solve the error.

index.ts
interface Employee { id: number; name: string | null; } const emp: Employee = { id: 1, name: 'Bobby Hadz', }; let name = ''; if (emp.name !== null) { name = emp.name; } console.log(name); // ๐Ÿ‘‰๏ธ "Bobby Hadz"

using an if statement to solve the error

The code for this article is available on GitHub

We used the let keyword to initialize the name variable to an empty string.

In the if statement, we check if the emp.name property is not equal to null and assign the name variable to the corresponding value.

The cause of the "Type 'string | null' is not assignable to type string" error is that the types of the values on the left and right-hand sides are not compatible.

If you get the "Object is possibly 'null'" error, check out my other article.

# Updating the type of the value to solve the error

Depending on your use case, you could solve the error by updating the type of the value to the left or right and making them compatible.

index.ts
interface Employee { id: number; name: string | null; } const emp: Employee = { id: 1, name: 'Bobby Hadz', }; // ๐Ÿ‘‡๏ธ const name: string | null const name: string | null = emp.name; console.log(name); // ๐Ÿ‘‰๏ธ "Bobby Hadz"

We explicitly set the type of the name variable to be string | null, which is the same type as the type of the name property in the Employee interface.

# Argument type 'string or null' not assignable to parameter of type string

The error "Argument of type 'string | null' is not assignable to parameter of type string" occurs when a possibly null value is passed to a function that expects a string.

To solve the error, use a type guard to verify the value is a string before passing it to the function.

argument type null not assignable parameter string

Here is an example of how the error occurs.

index.ts
function getMessage(message: string) { return message; } const value = Math.random() > 0.5 ? 'hello' : null; // โ›”๏ธ Error: Argument of type 'string | null' is not // assignable to parameter of type 'string'. // Type 'null' is not assignable to type 'string'.ts(2345) getMessage(value);

The function expects to get called with an argument of type string but the supplied argument is possibly null.

TypeScript is telling us that the value we are passing to the function might be null, which is not compatible with the type of the function's parameter which is a string.

# Using a non-null assertion to solve the error

One way to get around this is to use a non-null assertion.

index.ts
function getMessage(message: string) { return message; } const value = Math.random() > 0.5 ? 'hello' : null; getMessage(value!); // ๐Ÿ‘ˆ๏ธ non-null assertion
The code for this article is available on GitHub

The exclamation mark is the non-null assertion operator in TypeScript.

It removes null and undefined from a type without doing any explicit type-checking.

When you use this approach, you basically tell TypeScript that this value will never be null or undefined.

# Using a type assertion to solve the error

This is very similar to a type assertion and should only be used when you're absolutely sure that the value is of the expected type.

index.ts
function getMessage(message: string) { return message; } const value = Math.random() > 0.5 ? 'hello' : null; getMessage(value as string); // ๐Ÿ‘ˆ๏ธ type assertion
Type assertions are used when we have information about the type of a value that TypeScript can't know about.

We effectively tell TypeScript that the variable stores a string and not to worry about it.

# Using a type guard to solve the error

An alternative and much better approach is to use a type guard.

index.ts
function getMessage(message: string) { return message; } const maybeString = Math.random() > 0.5 ? 'hello' : null; const message: string = maybeString !== null ? maybeString : ''; getMessage(message);
The code for this article is available on GitHub

We used the ternary operator to check if the maybeString variable is not equal to null.

If it's not equal to null, it gets assigned to the message variable, otherwise, we use an empty string as a fallback.

This way we can be sure that the message variable will always get assigned a string, even if the maybeString variable is null.

# Using the nullish coalescing (??) operator to solve the error

You could also use the nullish coalescing operator (??) to solve the error.

index.ts
function getMessage(message: string) { return message; } const maybeString = Math.random() > 0.5 ? 'hello' : null; getMessage(maybeString ?? '');
The nullish coalescing operator (??) enables us to specify a fallback for when a value is null or undefined.

So, if the maybeString variable is null or undefined, we pass an empty string argument to the function.

# Using the logical OR (||) operator to solve the error

You can also use the logical OR (||) operator in a similar way.

index.ts
function getMessage(message: string) { return message; } const maybeString = Math.random() > 0.5 ? 'hello' : null; getMessage(maybeString || '');

The logical OR (||) operator returns the value to the right if the value to the left is falsy.

This is different than the nullish coalescing operator (??) because nullish coalescing only checks for null and undefined.

The logical OR (||) operator would return the value to the right if the value to the left is any of the following: null, undefined, false, 0, "" (empty string), NaN (not a number).

# Updating the type of the function's parameter to solve the error

The cause of the "Argument of type 'string | null' is not assignable to parameter of type string" error is that the type of the function's parameter and the type of the passed-in argument are not compatible.

Depending on your use case, you could also solve the error by updating the type of the function's parameter and making the parameter and the passed-in argument compatible types.

index.ts
// ๐Ÿ‘‡๏ธ parameter is type string or null function getMessage(message: string | null) { return message; } // ๐Ÿ‘‡๏ธ argument is also type string or null const maybeString = Math.random() > 0.5 ? 'hello' : null; getMessage(maybeString);
The code for this article is available on GitHub

The function's parameter is now typed as string or null, so we are able to pass it an argument of type string or null because the two types are compatible.

# Type 'null' is not assignable to type in TypeScript

Use a union type to solve the "Type 'null' is not assignable to type" error in TypeScript, e.g. name: string | null.

The type of the value has to accept null because if it doesn't and you have strictNullChecks enabled in tsconfig.json, the type checker throws the error.

Here is an example of how the error occurs.

index.ts
// ๐Ÿ‘‡๏ธ Function return value set to object function getObj(): Record<string, string> { if (Math.random() > 0.5) { // โ›”๏ธ Error Type 'null' is not assignable to type // 'Record<string, string>'.ts(2322) return null; } return { name: 'Bobby Hadz' }; }

And here is another example.

index.ts
interface Person { name: string; // ๐Ÿ‘ˆ๏ธ name property set to string } const obj: Person = { name: 'Bobby Hadz' }; // โ›”๏ธ Type 'null' is not assignable to type 'string'.ts(2322) obj.name = null;

The function in the first example returns a null value or an object, but we haven't specified that the function might return null.

The object in the second example has a type of string for the name property, but we are trying to set the property to null which causes the error.

# Using a union type to solve the error

You can use a union type to solve the error.

index.ts
// ๐Ÿ‘‡๏ธ using union function getObj(): Record<string, string> | null { if (Math.random() > 0.5) { return null; } return { name: 'Bobby Hadz' }; }
The code for this article is available on GitHub

And here is how to solve the interface example using a union.

index.ts
interface Person { // ๐Ÿ‘‡ using union name: string | null; } const obj: Person = { name: 'Bobby Hadz' }; obj.name = null;

We used a union type to set the return value of the function to either an object with string keys and values or null.

This approach allows us to return an object or a null value from the function.

In the second example, we set the name property in the object to have a type of string or null

Now we can set the property to a value of null without getting the error.

# Use a type guard to check if the property is not null

If you have to access the name property, e.g. to call the toLowerCase() method on it, you have to use a type guard, because the property is possibly null.

index.ts
interface Person { // ๐Ÿ‘‡ using union name: string | null; } const obj: Person = { name: 'Bobby Hadz' }; // โ›”๏ธ Error: 'obj.name' is possibly 'null' obj.name.toLowerCase();

You can get around this with a simple type guard.

index.ts
interface Person { // ๐Ÿ‘‡ using union name: string | null; } const obj: Person = { name: 'Bobby Hadz' }; if (obj.name !== null) { // โœ… Now obj.name is string console.log(obj.name.toLowerCase()); }

# Suppressing the error by setting strictNullChecks to false

The error can be suppressed by setting strictNullChecks to false in your tsconfig.json file.

tsconfig.json
{ "compilerOptions": { "strictNullChecks": false, // ... ๐Ÿ‘‡๏ธ rest } }

When strictNullChecks is set to false, null and undefined are ignored by the language.

This is not advisable as it can lead to unexpected errors at runtime.

When you set strictNullChecks to true, null and undefined have their own types and you get errors when using them when a value of a different type is expected.

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.

Copyright ยฉ 2024 Borislav Hadzhiev