microsoft / microsoft/TypeScript
[Suggestion] Compiler Flag to treat types as immutable
Nobody has claimed this yet.
- 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
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 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