Skip to content

JSX spread doesn't work with union props #18670

Closed

Description

@pelotom

TypeScript Version: 2.4.0 / nightly (2.5.0-dev.201xxxxx)

It's often useful to define a React component's properties as a union type, e.g.

type InfoProps =
  | { status: 'hidden' }
  | { status: 'visible'; content: string }

const Info = (props: InfoProps) =>
  props.status === 'hidden'
    ? <noscript />
    : <div>{props.content}</div>

When constructing elements from this component, it works fine in concrete cases:

<Info status="hidden" />
<Info status="visible" content="hello world" />

however if you try to use "spread" syntax, it's a type error:

declare const infoProps: InfoProps

<Info {...infoProps} />
/* .  ^^^^^^^^^^^^^^
Type '{ status: "hidden" | "visible"; }' is not assignable to type '(IntrinsicAttributes & { status: "hidden"; }) | (IntrinsicAttributes & { status: "visible"; conte...'.
  Type '{ status: "hidden" | "visible"; }' is not assignable to type 'IntrinsicAttributes & { status: "visible"; content: string; }'.
    Type '{ status: "hidden" | "visible"; }' is not assignable to type '{ status: "visible"; content: string; }'.
      Types of property 'status' are incompatible.
        Type '"hidden" | "visible"' is not assignable to type '"visible"'.
          Type '"hidden"' is not assignable to type '"visible"'.
*/

As I understand it, this should be no different semantically from

React.createElement(Info, infoProps)

which the compiler approves of.

Activity

  1. OliverJAsh commented on Sep 25, 2017

    @OliverJAsh
    Contributor

    Just hit on exactly the same problem, reproducible in 2.4.1 and 2.5.2. Another example:

    import React, { SFC } from 'react';
    
    {
        type CommonProps = { common: string };
        type Props = CommonProps &
            ({ type: 'foo' } | { type: 'bar'; message: string });
    
        const Button: SFC<Props> = (props) => null;
    
        const OtherButton1: SFC<Props> = (props) => React.createElement(Button, props);
    
        // Type '"foo"' is not assignable to type '"bar"'.
        const OtherButton2: SFC<Props> = (props) => <Button {...props} />;
    }
  2. locked and limited conversation to collaborators on Jun 14, 2018
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Labels

BugA bug in TypeScriptFixedA PR has been merged for this issue

Type

No type

Projects

No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions