microsoft / microsoft/TypeScript
Narrowing from `typeof x !== 'object'` incorrectly excludes functions.
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
typeof object function narrow, type narrowing
🕗 Version & Regression Information
Present in all recent versions from at least 3.3.3333 through the current nightly 4.4.0-dev.20210701
- This is the behavior in every version I tried, and I reviewed the FAQ for entries about "typeof" and "narrow"
⏯ Playground Link
💻 Code
let x!: string|object; // |Function;
if (1 < 2) x = () => 1;
if (typeof x !== 'object') {
useString(x); // should fail, but doesn't
}
declare function useString(s: string): void;
🙁 Actual behavior
The type narrowing for typeof x !== 'object' pruned the entire |object branch from x's type union, but typeof can return either "object" or "function" for values of type object, so this is overzealous. This causes x inside the conditional to be incorrectly narrowed to just string when we can clearly see from the earlier line that it's been assigned a function, which is incorrectly passed to useString with no complaint.
🙂 Expected behavior
Excluding "object" from typeof x should not remove |object from its type, in the same way that it doesn't narrow unknown any further. This would cause the appropriate type error from passing a function to useString.
Note that if an explicit |Function branch is added to to x's type union then the narrowing proceeds as expected.
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
Start with the linked TypeScript Playground and the provided narrowing example, then trace the type-narrowing logic for typeof x !== "object". The fix is done when a function assigned to x is not narrowed away and passing x to useString produces the expected type error; verify behavior against the stated versions.
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
- 45/100