18

In a TypeScript + React project I am using react-dnd with its DefinitelyTyped typings:

interface ExampleScreenProps { a, b, c }
interface ExampleScreenState { x, y, z }

class ExampleScreen extends React.Component<ExampleScreenProps, ExampleScreenState> { }

export default DragDropContext(HTML5Backend)(ExampleScreen);

This gets rendered in another component:

import ExampleScreen from "./ExampleScreen";

<ExampleScreen a="a" b="b" c="c" />

This works in TS 1.8 without any errors. When I upgraded to TS 2.0 I got the following compile error:

Error:(90, 10) TS2600: JSX element attributes type '(ExampleScreenProps & { children?: ReactNode; }) | (ExampleScreenProps & { children...' may not be a union type.

This is the type definition for DragDropContext:

export function DragDropContext<P>(
    backend: Backend
): <P>(componentClass: React.ComponentClass<P> | React.StatelessComponent<P>) => ContextComponentClass<P>;

I can't put this together. What is the error complaining about? It seems that it doesn't like the union of ComponentClass<P> | StatelessComponent<P>, yet those are not the element attributes, the element attributes are simply <P>. I tried explicitly passing <P>:

export default DragDropContext<ExampleProps>(HTML5Backend)(ExampleScreen);

But the same error remains. I can workaround it by asserting the output:

export default DragDropContext(HTML5Backend)(ExampleScreen) as React.ComponentClass<ExampleProps>;

But I don't like having to use an assertion and I don't understand the actual problem, or if I'm doing something wrong. Is this a problem with the typings that can be fixed?

Junle Li
  • 1,035
  • 1
  • 12
  • 18
Aaron Beall
  • 49,769
  • 26
  • 85
  • 103
  • 1
    Thinking about this, I guess the error may be caused because `

    ` for a component class has the implicit props `{key, children, ref}` but stateless components don't have all of those props, so the result is not the same. Still, I don't see why TS can't infer that the type is a `ComponentClass` and not a `StatelessComponent`.

    – Aaron Beall Oct 31 '16 at 13:15
  • If this is the same as [this](https://github.com/Microsoft/TypeScript/issues/13526), then apparently it's being addressed in [this PR](https://github.com/Microsoft/TypeScript/pull/12107). – Drew Noakes Jan 23 '17 at 16:02

2 Answers2

1

no build error with typescript 2.4.2
and used dependencies:

    "react": "^15.6.1",
    "react-dom": "^15.6.1",
    "react-dnd":"^2.4.0"

    "@types/react": "^16.0.5",
    "@types/react-dom": "^15.0.0",
    "@types/react-dnd":"^2.0.33",
Mario
  • 11
  • 2
0

You can install the new typings using:

npm i @types/react-dnd --save-dev

if you already install other typings remove it using:

typings uninstall --save --global react-dnd

After that it should work as expected.

Eyal Ofri
  • 680
  • 10
  • 16