Skip to content

JSX spread doesn't work with union props #18670

Closed
@pelotom

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.

Metadata

Metadata

Assignees

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