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

bug in type narrowing #46885

Closed
ARZarkesh opened this issue Nov 21, 2021 · 2 comments
Closed

bug in type narrowing #46885

ARZarkesh opened this issue Nov 21, 2021 · 2 comments
Labels
Duplicate An existing issue was already created

Comments

@ARZarkesh
Copy link

Bug Report

I wrote a helper type to making some fields of object optional. But I got the following error in type narrowing.

πŸ”Ž Search Terms

type narrowing, optionalize

πŸ•— Version & Regression Information

  • 4.4.4

⏯ Playground Link

Playground link with relevant code

πŸ’» Code

type Optionalize<T, K extends keyof T> = Omit<T, K> & { [Key in K]: T[K] | undefined }

type API = { x: number, y: string }

function send(input: Optionalize<API, 'y'>): API {
  if (input.y === undefined) throw new Error('invalid input')

  return input
}

πŸ™ Actual behavior

input.y is string | undefined

πŸ™‚ Expected behavior

I expected input.y to be string

@MartinJohns
Copy link
Contributor

Your described actual behaviour is wrong. The actual behaviour is what you describe in expected behaviour. The type of input.y is narrowed to string, it is not string | undefined anymore.
image


You expect the type of input to be narrowed to API, but that's not supported.

Quoting @jack-williams:

Type guards do not propagate type narrowings to parent objects. The narrowing is only applied upon access of the narrowed property which is why the destructing function works, but the reference function does not. Narrowing the parent would involve synthesizing new types which would be expensive. More detail in this comment.

Used search terms: type guard property parent

@RyanCavanaugh RyanCavanaugh added the Duplicate An existing issue was already created label Nov 22, 2021
@typescript-bot
Copy link
Collaborator

This issue has been marked as a 'Duplicate' 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
Duplicate An existing issue was already created
Projects
None yet
Development

No branches or pull requests

4 participants