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.