microsoft / microsoft/TypeScript

TS2454 Variable is used before being assigned with strictNullChecks when variable is clearly assigned but can be undefined

Open
#59,804 1 comment 7 reactions 1 assignee View on GitHub

@RyanCavanaugh is already working on this.

Since Aug 30, 2024.

Bug Domain: check: Control Flow
Dominant language
Go
Stars
111k
Forks
14.3k
Avg merge
1d 19h
Merged PRs (30d)
117

Description

🔎 Search Terms

Variable is used before being assigned TS2454 TS(2454) undefined strictNullChecks

🕗 Version & Regression Information
  • This happens at least since version 3.7.5 (tested in the playground)
  • This is the behavior in every version I tried, and I reviewed the FAQ
⏯ Playground Link

https://www.typescriptlang.org/play/?#code/DYUwLgBGIM6QvBArgOwCYgGYEsUjQNwBQR0cEiA5JRAIYwRwBOuA5hAD7Lpa77GlYYAPwA6UClZgAFgSA

💻 Code
let test = undefined;

test = '' as string | undefined;

test?.length; // Variable 'test' is used before being assigned.
🙁 Actual behavior

Typescript throws an error complaining about test being used before being assigned but it's clearly assigned to undefined and then to ''.

Mine is a very simplicistic problem, but the same issues happens if a replace '' with a call to a function.

🙂 Expected behavior

Typescript should assign the type string | undefined to the variable test and let me use it.

Additional information about the issue

No response

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.