Skip to content

TypeScript doesn't correctly typecheck React/JSX union properties #10171

Closed
@gcnew

Description

@gcnew

TypeScript Version: nightly (2.1.0-dev.20160805)

Code

import * as React from "react";
import * as ReactDOM from "react-dom";

type TextProps = { editable: false }
               | { editable: true, onEdit: (newText: string) => void }

class TextComponent extends React.Component<TextProps, {}> {
    render() {
        return <span>Some Text..</span>;
    }
}

ReactDOM.render(
    <TextComponent editable={true} />, // FAIL: should be an error, but it's not
                                       // `onEdit` is missing
    document.getElementById("example")
);

// OK: correctly issues an error
React.createElement(TextComponent, { editable: true as true });

Unfortunately, not only is the parameter presence not enforced, but also it cannot be provided even if the programmer somehow notices:

ReactDOM.render(
    // Property 'onEdit' does not exist on type ...
    <TextComponent editable={true} onEdit={ () => {} } />,
    document.getElementById("example")
);

Type-safe workaround:

const textProps: TextProps = {
    editable: true as true,  // Whoops, why not literal type?
    onEdit: () => {}
};

ReactDOM.render(
    <TextComponent {...textProps} />,
    document.getElementById("example")
);

Expected behavior:
The compiler should check whether the provided property set in JSX syntax matches the expected one according to the normal typing rules.

PS: Is there a way to see the desugarred TS?

Metadata

Metadata

Assignees

No one assigned

    Labels

    BugA bug in TypeScriptDomain: JSX/TSXRelates to the JSX parser and emitter

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions