Skip to content

Type inference problem with generics and Readonly #26600

Closed
@jbialobr

Description

@jbialobr

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    Design LimitationConstraints of the existing architecture prevent this from being fixed

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions