HiveBrain v1.2.0
Get Started
← Back to all entries
patterntypescriptCritical

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

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
typeassignablenotnull

Problem

I have this generic method

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 null or turn off strictNullChecks in your tsconfig

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


or you could type null as any e.g.

return null as any;

Code Snippets

public static bar<T>(x: T): T | null
return null as any;

Context

Stack Overflow Q#59715119, score: 264

Revisions (0)

No revisions yet.