microsoft / microsoft/TypeScript

HOC returned component props can not differ from HOC generic props

Open
#28,938 26 comments 80 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Bug Domain: JSX/TSX Needs Human Review
Dominant language
Go
Stars
111k
Forks
14.3k
Avg merge
2d 4h
Merged PRs (30d)
132

Description

TypeScript Version: 3.3.0-dev.20181208

Search Terms:

  • HOC
  • react
  • higher order component

Code

import * as React from 'react';

export interface HOCProps {
  foo: number;
}

/** Remove props, that have been prefilled by the HOC */
type WithoutPrefilled<T extends HOCProps> = Pick<T, Exclude<keyof T, 'foo'>>;

function withFoo<P extends HOCProps>(WrappedComponent: React.ComponentType<P>) {
  return class SomeHOC extends React.Component<WithoutPrefilled<P>> {
    public render(): JSX.Element {
      return <WrappedComponent {...this.props} foo={0} />;
    }
  };
}

Expected behavior:
No error, like with every version below 3.2.0.

Actual behavior:
Throws an error highlighting the WrappedComponent in the render method.

[ts]
Type 'Readonly<{ children?: ReactNode; }> & Readonly<Pick<P, Exclude<keyof P, "foo">>> & { foo: number; }' is not assignable to type 'IntrinsicAttributes & P & { children?: ReactNode; }'.
  Type 'Readonly<{ children?: ReactNode; }> & Readonly<Pick<P, Exclude<keyof P, "foo">>> & { foo: number; }' is not assignable to type 'P'. [2322]

Additional Information

This is pretty much the same sample example used in https://github.com/Microsoft/TypeScript/issues/28720, but with the difference, that the props of the returned component differ from the generic.

Basically the HOC prefills the foo property for the WrappedComponent. Since the spreaded props are overriden by foo, I don’t want foo to be a valid property for the HOC. This does not seem to be possible anymore.

Playground Link:

Related Issues:
https://github.com/Microsoft/TypeScript/issues/28720

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start by reproducing the HOC example with the reported TypeScript version and compare it with the behavior before 3.2. Read the related issue 28720 and locate the type-checking tests for JSX generic components and spread props. Done means the sample type-checks without error while keeping foo supplied by the HOC rather than accepted as a returned component prop.

Written by the indexing model from the issue text.

Assessment

Tech stack
react, typescript
Domain
compilers
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Active
Clarity
Mostly clear
Newbie friendliness
48/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.