Skip to content

Type narrowing for object literal being defined and returned in place behaves differently with variable indirectionΒ #43966

Closed
@devversion

Description

@devversion

Bug Report

πŸ”Ž Search Terms

type narrowing, typescript 4.3, generic, instance type spread, instance type spread in return object literal, spread operator cloning

πŸ•— Version & Regression Information

this started when updating 4.3 beta

⏯ Playground Link

https://www.typescriptlang.org/play?ts=4.3.0-beta#code/JYOwLgpgTgZghgYwgAgPJTiA5ig3gKGSORDgFsIAuZAZzClCwG58BfffUSWRFAQQAOAgDZ5CxUhWp0G2Fu3wwAriARhgAexDJIdADwAVZBAAekEABMayQSIgAfdJhwA+ABTBIZagYCUP5AJiZCgIMCUobVwAOljPCDJWeQ5lVXUtHQg6ACZDYzMIS2tbUUcMbAh3eO9kPwCg4gQtOmQTZABeQNjo6qTxIlDwyNb5IA

πŸ’» Code

interface Orange {
    name: string;
}

interface Apple {
    name: string;
}

function test<T extends Apple|Orange>(item: T): T {
    
  // fails with: '{ name: string; }' is assignable to the constraint of type 'T', but 'T' could be instantiated with
  // a different subtype of constraint 'Orange | Apple'.(2322)
  return {...item};
}

function test2<T extends Apple|Orange>(item: T): T {
    const x = {...item};
    // this works due to the indirection w/ a variable declaration resolving the type to `T`
    return x;
}

πŸ™ Actual behavior

TypeScript behaves inconsistently when the instance is cloned using spread operator, depending on
whether the spread operator is used in an object literal as variable initializer, or as direct value for a return statement.

πŸ™‚ Expected behavior

TypeScript should narrow the type consistently; so that no errors are reported inconsistently.

Metadata

Metadata

Assignees

Labels

BugA bug in TypeScriptFix AvailableA PR has been opened for this issue

Type

No type

Projects

No projects

Relationships

None yet

Development

No branches or pull requests

Issue actions