Closed
Description
TypeScript Version: 3.0.1
Search Terms:
Type inference generics Readonly
Code
class ReactComponent<P>
{
public constructor(public props: Readonly<P>)
{
}
}
interface XampleProps
{
x?: boolean;
}
class Xample<PT extends XampleProps = XampleProps> extends ReactComponent<PT>
{
public render()
{
const localX = this.props.x;
return this.doSthWithX(localX || false);
}
private doSthWithX(data: boolean): boolean
{
return data;
}
}
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.
class Xample<PT extends XampleProps = XampleProps> extends ReactComponent<PT>
{
public render()
{
const localX: boolean | undefined = this.props.x;
return this.doSthWithX(localX || false);
}
private doSthWithX(data: boolean): boolean
{
return data;
}
}
Removing the Readonly
from the ReactComponent also eliminates the compiler error.
Playground Link:
Related Issues:
Perhaps #26418