Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Closed
devversion opened this issue May 5, 2021 · 1 comment Β· Fixed by #44002
Assignees
Labels
Bug A bug in TypeScript Fix Available A PR has been opened for this issue

Comments

@devversion
Copy link
Contributor

devversion commented May 5, 2021

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.

@RyanCavanaugh RyanCavanaugh added the Bug A bug in TypeScript label May 6, 2021
@RyanCavanaugh RyanCavanaugh added this to the TypeScript 4.3.1 milestone May 6, 2021
@sandersn
Copy link
Member

sandersn commented May 7, 2021

Broken by #43183

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Bug A bug in TypeScript Fix Available A PR has been opened for this issue
Projects
None yet
Development

Successfully merging a pull request may close this issue.

5 participants