TypeScript Version: 3.0.1
Search Terms:
Type inference generics Readonly
Code
classReactComponent<P>{publicconstructor(publicprops: Readonly<P>){}}interfaceXampleProps{x?: boolean;}classXample<PTextendsXampleProps=XampleProps>extendsReactComponent<PT>{publicrender(){constlocalX=this.props.x;returnthis.doSthWithX(localX||false);}privatedoSthWithX(data: boolean): boolean{returndata;}}Expected behavior:
Code should compile with no errors.
Actual behavior:
The compiler complains about the return this.doSthWithX(localX || false); line. It says:
Argument of type 'PT["x"]' is not assignable to parameter of type 'boolean'.
Type 'boolean | undefined' is not assignable to type 'boolean'.
Type 'undefined' is not assignable to type 'boolean'.
Adding the explicit type for localX solves the problem.
classXample<PTextendsXampleProps=XampleProps>extendsReactComponent<PT>{publicrender(){constlocalX: boolean|undefined=this.props.x;returnthis.doSthWithX(localX||false);}privatedoSthWithX(data: boolean): boolean{returndata;}}Removing the Readonly from the ReactComponent also eliminates the compiler error.
Playground Link:
Related Issues:
Perhaps #26418
TypeScript Version: 3.0.1
Search Terms:
Type inference generics Readonly
Code
Expected behavior:
Code should compile with no errors.
Actual behavior:
The compiler complains about the
return this.doSthWithX(localX || false);line. It says:Adding the explicit type for
localXsolves the problem.Removing the
Readonlyfrom the ReactComponent also eliminates the compiler error.Playground Link:
Related Issues:
Perhaps #26418