patterntypescriptCritical
Type 'null' is not assignable to type 'T'
Viewed 0 times
typeassignablenotnull
Problem
I have this generic method
I'm getting the syntax error
TS2322: Type 'null' is not assignable to type 'T'.
I'm expecting this to compile because
what is the proper way to solve this problem
class Foo {
public static bar(x: T): T {
...
if(x === null)
return 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
Solution
You have to declare the return type as
or you could type null
null or turn off strictNullChecks in your tsconfigpublic static bar(x: T): T | nullor you could type null
as any e.g.return null as any;Code Snippets
public static bar<T>(x: T): T | nullreturn null as any;Context
Stack Overflow Q#59715119, score: 264
Revisions (0)
No revisions yet.