microsoft / microsoft/TypeScript
Non-null assertion operator whitespace allowances can create confusing conditional statements
Nobody has claimed this yet.
- Dominant language
- Go
- Stars
- 111k
- Forks
- 14.3k
- Avg merge
- 2d 4h
- Merged PRs (30d)
- 132
Description
🔎 Search Terms
You can write a non-null assertion operator with whitespace after a variable name and no white space before certain keywords such as in and instanceof and the type checker doesn't fail but instead strips the operator creating the opposite condition as it appears.
To a someone not familiar with TypeScript/JavaScript key !in obj reads like if key not in obj . To them this might be if the tsc treated key !== 'a' as key == 'a'
🕗 Version & Regression Information
- This changed between versions N/A and N/A
- This changed in commit or PR N/A
- This is the behavior in every version I tried, and I reviewed the FAQ for entries about Common "Bugs" That Aren't Bugs
- I was unable to test this on prior versions because N/A
⏯ Playground Link
💻 Code
const foo: {a?: string} = {a: 'bar'};
const key = 'a' as const;
if (key !in foo) {
// non-null operator stripped and key exists in obj
console.log(foo[key]);
}
if (foo !instanceof Object) {
// non-null operator stripped and obj is Object
console.log(typeof foo);
}
🙁 Actual behavior
The TSC stripped the non-null assertion, the operator should not be considered a non-null operator at all in this situation.
🙂 Expected behavior
I would expect a syntax error in this situation.
Additional information about the issue
This is a real problem not just hypothetical, I noticed a discussion started by a person learning typescript complaining about how their code was evaluating true regardless of the "negation operator" being used before the in keyword.
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 examples from the Playground link with tsc, focusing on the whitespace before in and instanceof. Trace how these expressions are parsed and validated, then add regression coverage demonstrating that the forms produce a syntax error rather than stripping the non-null assertion.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- javascript, typescript
- Domain
- compilers
- Issue type
- Bug
- Difficulty
- 4/5
- Estimated time
- 3-5 days
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 35/100