microsoft / microsoft/TypeScript

[Suggestion] Compiler Flag to treat types as immutable

Open
#16,317 4 comments 6 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

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

Description

TypeScript Version: 2.3.4

Code

I'm aware of #10725, but I want to take it one step further and add a compiler flag (e.g. --immutable) that will cause the compiler to infer Readonly, ReadonlyArray, ReadonlyMap, and ReadonlySet (and any other data structures I've missed) everywhere. The flag will also force you to use const. Thus eliminating mutability from the language.

// tsconfig.json

{
  "compilerOptions": {
    "immutable": true
  }
}
// demo.ts

// band is automatically inferred as:
// Readonly<{
//   name: string;
//   members: ReadonlyArray<{
//     name: string;
//     instruments: ReadonlyArray<string>;
//   }>;
// }>
const band = {
  name: 'U2',
  members: [
    {
      name: 'Bono',
      instruments: ['vocals', 'rhythm guitar', 'harmonic']
    },
    {
      name: 'The Edge',
      instruments: ['lead guitar', 'keyboards', 'backing vocals']
    },
    // ...
  ]
};

// The following will cause compiler errors:
// band.name = 'Green Day';
// band.members.push({ name: 'Billie Joe Armstrong', instruments: ['lead vocals', 'guitar'] });

// ----------------------------------------------------------------------

// numberMap is automatically inferred to be ReadonlyMap<number, string>
const numberMap = new Map<number, string>([
  [1, 'one'],
  [2, 'two']
]);

// Compiler error:
// numberMap.set(3, 'three');

// letterSet is is automatically inferred to be ReadonlySet<string>
const letterSet = new Set<string>(['A', 'B', 'C', 'D']);

// Compiler error:
// letterSet.add('E');

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 reviewing the proposal, the referenced issue #10725, and the linked TypeScript design-proposal guidance. Define the compiler-option behavior for const enforcement and readonly inference across the examples and other data structures; the issue provides no files or tests to run, so completion would require an agreed design and corresponding coverage.

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
30/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.