Type 'null' is not assignable to type 'T'
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
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;
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
intsconfig.json
. - Declare your variable type as
any
:let x: any = null;
You can put
return null!;
It worked for me