Skip to content

Error using intersection type for object rest destructuring #12520

Closed

Description

This is using the latest release-2.1 branch. I'm unclear why types B & C would behave differently below when it comes to object rest members, so I am assuming this is a bug. (ping Nathan Shively-Sanders (@sandersn) & Mohamed Hegazy (@mhegazy) ).

interface A {
    name: string;
    age: number;
}

interface B extends A {
    address: string;
}

type C = A & {address: string};

// Both v1 & v2 appear to have the same members...
var v1: B;
var v2: C;

// ... and assignment in either direction is fine
v1 = v2; // OK
v2 = v1; // OK

// let {name, ...x2} = v1;  // This line is valid (when uncommented)
let {name, ...x3} = v2;  // This line gives the error: Rest types may only be created from object types.

Activity

  1. sandersn commented on Nov 27, 2016

    @sandersn
    Member
  2. billti commented on Nov 27, 2016

    @billti
    MemberAuthor

    My scenario was in trying to type a tree of React components, whereby (parts of) the model gets passed down, yet some components may also add members for some children (such as event handlers). A simplified/contrived example is below. Without intersection types working, I had to extend an interface each time I wanted to augment the type of the receiving props parameter.

    let model = {
        a: "test",
        b: 42,
        c: true
    };
    type Model = typeof model;
    
    function Comp1(model: Model){
        let clickHandler = (e: Event) => {return true;};
        return <Comp2 onClick={clickHandler} {...model}></Comp2>;
    }
    
    function Comp2({...props}: Model & {onClick: Function}){ // <- Gives an error currently
        return <div></div>;
    }

    Note: Subtraction types will be nice too, as often you remove a couple of props from the model then pass down the remainder - which is kind of a pain to describe accurately right now without a lot of forethought (and code).

  3. added
    BugA bug in TypeScript
    and removed
    Working as IntendedThe behavior described is the intended behavior; this is not a bug
    on Nov 28, 2016
  4. added this to the milestone on Nov 28, 2016
  5. mhegazy commented on Nov 28, 2016

    @mhegazy
    Contributor

    In cases like these we should just allow it to go through. it is rather artificial that we do not. type parameters should still be disallowed though.

  6. locked and limited conversation to collaborators on Jun 19, 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