Categories
TypeScript Answers

How to fix the “Type ‘null’ is not assignable to type ‘T'” error in TypeScript?

Spread the love

Sometimes, we want to fix the "Type ‘null’ is not assignable to type ‘T’" error in TypeScript.

In this article, we’ll look at how to fix the "Type ‘null’ is not assignable to type ‘T’" error in TypeScript.

How to fix the "Type ‘null’ is not assignable to type ‘T’" error in TypeScript?

To fix the "Type ‘null’ is not assignable to type ‘T’" error in TypeScript, we call add null as one of the return types of our function.

For instance, we write

class Foo {
  public static bar<T>(x: T): T | null {
    //...
    if (x === null) {
      return null;
    }
    //...
  }
}

to add the null type of as one of the data types that can be returned by the bar method in addition to the generic T type.

Conclusion

To fix the "Type ‘null’ is not assignable to type ‘T’" error in TypeScript, we call add null as one of the return types of our function.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

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