microsoft / microsoft/TypeScript
Type narrowing down on a union type with null results in incorrect type when applying `typeof`
Nobody has claimed this yet.
- Dominant language
- Go
- Stars
- 111k
- Forks
- 14.4k
- Avg merge
- 1d 19h
- Merged PRs (30d)
- 117
Description
Bug Report
🔎 Search Terms
type narrowing down, typeof
🕗 Version & Regression Information
I've tested all versions until 4.4.0 (Nightly)
⏯ Playground Link
💻 Code
type Container = { container: {type: "foo"} | {type: "bar"} | null }
function test(input: Container) {
if (input.container?.type === 'foo') {
// works
acceptsFoo(input.container);
acceptsFoo({type: "foo"})
// Does not works
acceptsFoo(input.container as typeof input.container)
acceptsFoo({type: "foo"} as typeof input.container)
/**
Error:
Argument of type '{ type: "foo"; } | null' is not assignable to parameter of type '{ type: "foo"; }'.
Type 'null' is not assignable to type '{ type: "foo"; }'.(2345) \
**/
}
}
function acceptsFoo(input: {type: "foo"}) {}
🙁 Actual behavior
input.container and input.container as typeof input.container are not equivalent.
🙂 Expected behavior
input.container and input.container as typeof input.container should be equivalent.
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
Reproduce the reported narrowing behavior in the linked TypeScript Playground using the provided Container and test function. Start by tracing the type-checker handling of optional property narrowing and typeof assertions; done means input.container and input.container as typeof input.container are treated equivalently without the nullability error.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- typescript
- Domain
- compilers
- Issue type
- Bug
- Difficulty
- 4/5
- Estimated time
- 3-5 days
- Activity status
- Stale
- Clarity
- Clearly specified
- Newbie friendliness
- 35/100