Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.7k views
in Technique[技术] by (71.8m points)

typescript - 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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...