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

Destructure and spread on generics not typing #33579

Closed
saulshanabrook opened this issue Sep 24, 2019 · 2 comments
Closed

Destructure and spread on generics not typing #33579

saulshanabrook opened this issue Sep 24, 2019 · 2 comments
Labels
Working as Intended The behavior described is the intended behavior; this is not a bug

Comments

@saulshanabrook
Copy link

TypeScript Version: 3.7.0-dev.20190924

Search Terms: destructure spread generic

Code

function test<T extends {key: number}>({key, ...rest}: T): T {
  return {key: 10, ...rest}
}

Expected behavior:

No type errors

Actual behavior:

Type '{ key: number; } & Pick<T, Exclude<keyof T, "key">>' is not assignable to type 'T'.
  '{ key: number; } & Pick<T, Exclude<keyof T, "key">>' is assignable to the constraint of type 'T', but 'T' could be instantiated with a different subtype of constraint '{ key: number; }'.

Playground Link: https://www.typescriptlang.org/play/index.html?ts=Nightly#code/GYVwdgxgLglg9mABFApgZygHgCqJQD1TABM1EBvAaxQE8AuRMEAWwCMUAnAXwD4AKKrQA0iAHTiO6KFwbYAlLIoBYAFCJEkqCA5JB9RAEYADCPGjJGLqq5A

Related Issues: #26412 #10727 #28234 #28312 #18552

@Nathan-Fenner
Copy link
Contributor

Nathan-Fenner commented Sep 24, 2019

This is behaving as expected, since you don't know that 10 is a valid value of type T["key"]. In particular, consider:

const example: {key: 1 | 2, val: string} = {key: 1, val: "abc"};

// No type error! But it would be wrong:
const sameType: {key: 1|2, val: string} = test(example);

So you'd need to instead give a type like:

function test<T extends {key: number}>({key, ...rest}: T): Omit<T, "key"> & {key: number} {
  return {key: 10, ...rest};
}

or like (but this one TypeScript also rejects, which is a design limitation since its flow-sensitive typing is not smart enough):

function test<T extends {key: number}>({key, ...rest}: T): number extends T["key"] ? T : Omit<T, "key"> & {key: number} {
  return {key: 10, ...rest}
}

@RyanCavanaugh RyanCavanaugh added the Working as Intended The behavior described is the intended behavior; this is not a bug label Sep 25, 2019
@typescript-bot
Copy link
Collaborator

This issue has been marked 'Working as Intended' and has seen no recent activity. It has been automatically closed for house-keeping purposes.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Working as Intended The behavior described is the intended behavior; this is not a bug
Projects
None yet
Development

No branches or pull requests

4 participants