Type 'null' can't be assigned to type 'T'

?

The following generic method has a syntax error:

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

This produces the error:

TS2322: Type ‘null’ is not assignable to type ‘T’.

How can this be fixed so that the code compiles when T is null?

To fix the error and allow the code to compile when T is null, you can use the type assertion as T to explicitly cast null to type T. Here’s the corrected code:

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

By using null as T, you tell the TypeScript compiler that although null is not assignable to type T, you want to override this and treat null as type T.