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

Propagating information from type guards to parent objects #55422

Closed
5 tasks done
fabiospampinato opened this issue Aug 17, 2023 · 3 comments
Closed
5 tasks done

Propagating information from type guards to parent objects #55422

fabiospampinato opened this issue Aug 17, 2023 · 3 comments

Comments

@fabiospampinato
Copy link

πŸ” Search Terms

  • narrowing
  • parent
  • propagate

βœ… Viability Checklist

  • This wouldn't be a breaking change in existing TypeScript/JavaScript code
  • This wouldn't change the runtime behavior of existing JavaScript code
  • This could be implemented without emitting different JS based on the types of the expressions
  • This isn't a runtime feature (e.g. library functionality, non-ECMAScript syntax with JavaScript output, new syntax sugar for JS, etc.)
  • This feature would agree with the rest of our Design Goals: https://github.com/Microsoft/TypeScript/wiki/TypeScript-Design-Goals

⭐ Suggestion

An example is worth a 1000 words:

type Process = undefined | {
  exitCode: number | null
}

const isNull = ( value: unknown ): value is null {
  return value === null;
};

let process: Process;

if ( isNull ( process?.exitCode ) ) {
  process.exitCode
  // ^?
}

We are narrowing process.exitCode, but indirectly we should be also narrowing the parent objects, which in this case is just process. Basically if process.exitCode is null then process can't be undefined, still, TS thinks it might still be.

πŸ“ƒ Motivating Example

See above.

πŸ’» Use Cases

Generally the smarter the type checker the better, and the cleaner the code you can write gets.

@fabiospampinato fabiospampinato changed the title Propagating type guards to parent objects Propagating information from type guards to parent objects Aug 17, 2023
@MartinJohns
Copy link
Contributor

Duplicate of #42384.

@fabiospampinato
Copy link
Author

Aaaaah, missed that, thanks!

@fatcerberus
Copy link

@fabiospampinato Note that this form of narrowing (narrowing a parent object to be non-null off the result of an optional chain) actually already works when done inline:

let process: Process;

if (process?.exitCode === null) {
  process.exitCode  // ok
}

Playground link

Not sure why it doesn't work with UDTGs. I guess technically a type predicate can lie but the compiler generally assumes they don't.

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

3 participants