Skip to content

Narrowing works incorrectly when destructuring #50604

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

Closed
tatomyr opened this issue Sep 2, 2022 · 5 comments
Closed

Narrowing works incorrectly when destructuring #50604

tatomyr opened this issue Sep 2, 2022 · 5 comments

Comments

@tatomyr
Copy link

tatomyr commented Sep 2, 2022

Bug Report

πŸ”Ž Search Terms

destructure, union, narrowing

πŸ•— Version & Regression Information

v.4.7.4, v4.8.0-beta.

⏯ Playground Link

Playground link

πŸ’» Code

const removeX = <T, X>({x, ...rest}: T & {x: X}): T => rest

πŸ™ Actual behavior

It produces the following error:

Type 'Omit<T & { x: X; }, "x">' is not assignable to type 'T'.
  'T' could be instantiated with an arbitrary type which could be unrelated to 'Omit<T & { x: X; }, "x">'.

πŸ™‚ Expected behavior

There should be no error since Omit<T & { x: X; }, "x"> is essentially equal to T.

@IllusionMH
Copy link
Contributor

Not if T contains property x. Then rest wont match T exactly.

@tatomyr
Copy link
Author

tatomyr commented Sep 2, 2022

Well, that's the part I'd expect Typescript to figure out for me that T does not contain x as I'm extracting it from whatever type is coming into my function.

@fatcerberus
Copy link

fatcerberus commented Sep 2, 2022

The return value is guaranteed not to contain property x. This is not guaranteed of T, because you can supply type arguments explicitly at the call site. It's a common mistake to write generic functions assuming the type parameter(s) are always inferred, but the compiler knows better.

@jakebailey
Copy link
Member

Perhaps this is sufficient for your use case?

function removeX<T extends Record<string, any>>({x, ...rest}: T): Omit<T, "x"> {
    return rest;
}

Playground Link

@tatomyr
Copy link
Author

tatomyr commented Sep 3, 2022

Thanks all for the explanations!
Now I see what the point is.

@tatomyr tatomyr closed this as completed Sep 3, 2022
@tatomyr tatomyr closed this as not planned Won't fix, can't repro, duplicate, stale Sep 3, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

4 participants