Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Type 'null' is not assignable to type 'T'

Tags:

typescript

I have this generic method

class Foo {       public static bar<T>(x: T): T {          ...          if(x === null)              return null; //<------- syntax error          ...      }  }   ... //somewhere const x = Foo.bar<number | null>(1); 

I'm getting the syntax error

TS2322: Type 'null' is not assignable to type 'T'.

I'm expecting this to compile because T could be null.

what is the proper way to solve this problem

like image 206
Ali Faris Avatar asked Jan 13 '20 10:01

Ali Faris


People also ask

How do I fix type null is not assignable to type string?

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.

Is not assignable to parameter of type null?

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. Here is an example of how the error occurs.

Is not assignable to type null react?

To fix 'Type 'null' is not assignable to type 'HTMLInputElement” error in React and TypeScript, we can create a type guard function. Then we use that to check if the ref is an HTMLInputElement . to create the isInputElement type guard. Then we check if elem is falsy and return false if it is.

Is not assignable to type null undefined?

The "Type 'undefined' is not assignable to type" error occurs when a possibly undefined value is assigned to something that expects a different type. To solve the error, use the non-null assertion operator or a type guard to verify the value is of the specific type before the assignment.


2 Answers

You have to declare the return type as null or turn off strictNullChecks in your tsconfig

public static bar<T>(x: T): T | null 

or you could type null as any e.g.

 return null as any; 
like image 125
Murat Karagöz Avatar answered Sep 16 '22 14:09

Murat Karagöz


Since version 3.9.5, TypeScript enforces strictNullChecks on numbers and strings just to name a few. For example, the following code will throw an error during compilation:

let x: number = null; 

To avoid this error you have two options:

  • Set strictNullChecks=false in tsconfig.json.
  • Declare your variable type as any:
    let x: any = null; 
like image 37
Hamfri Avatar answered Sep 19 '22 14:09

Hamfri