microsoft / microsoft/TypeScript

Proposal: Follow program flow in constructor when strictPropertyInitialization = true

Open
#30,462 13 comments 27 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

In Discussion Suggestion
Dominant language
Go
Stars
111k
Forks
14.3k
Avg merge
2d 4h
Merged PRs (30d)
132

Description

Search Terms

constructor strictPropertyInitialization flow

Suggestion

TypeScript should follow unconditional function calls in constructor when checking for strict property initialization.

Use Cases

It is a common pattern to be able to reset objects after construction and, thus, to transfer object initialization to a separate routine:

class C
{
  private p: number;

  public constructor() { Initialize() }

  public Initialize() { p = 0; }
}

Currently, TypeScript doesn't consider functions being unconditionally called from within a constructor function when checking for strict property initialization. The above code yields a compiler error.

I propose TypeScript to be able to analyse code flow and recognize property initialization that's performed in functions unconditionally called by the constructor function.

Checklist

My suggestion meets these guidelines:

  • 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, etc.)
  • This feature would agree with the rest of TypeScript's Design Goals.

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.

Research direction

Start by tracing the compiler's strictPropertyInitialization checks for constructors and unconditional function calls; the issue names no files or tests. Determine how control flow through a separately defined Initialize method should affect property initialization, then add coverage showing that the example is accepted while non-unconditional calls remain rejected.

Written by the indexing model from the issue text.

Assessment

Tech stack
typescript
Domain
compilers
Issue type
Feature
Difficulty
5/5
Estimated time
Over a week
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
25/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.