microsoft / microsoft/TypeScript
Pedantic: deny mutable type generalization
Nobody has claimed this yet.
- Dominant language
- Go
- Stars
- 111k
- Forks
- 14.3k
- Avg merge
- 2d 4h
- Merged PRs (30d)
- 132
Description
Search Terms
type generalization
type expanding
Suggestion
Currently we have a vulnerability in type safety of mutable variables. You can generalize the type of some variable and change its value by passing there something not compatible with the old type. Examples:
const a: Array<number> = [1, 2]
const b: Array<number | string> = a
b.push('a is not array of numbers anymore')
const a = { data: 0 }
function b (param: { data: string | number }) {
param.data = 'a is broken now'
}
b(a)
So I suggest adding a new compiler option under 'pedantic' label which will deny such type conversions:
const a: Array<number> = [1, 2]
// Error: type 'Array<number>' is not assignable to 'Array<number | string>'
const b: Array<number | string> = a
const a: Array<number> = [1, 2]
// OK: 'ReadonlyArray' won't let us mutate the state of 'a'
const b: ReadonlyArray<number | string> = a
const a = { foo: 0, bar: 'string' }
function b (param: { readonly foo: number | string, bar: string }) {
param.bar = String(param.foo)
}
// OK
// property 'foo: number' is assignable to 'readonly foo: number | string'
// property 'bar: string' is assignable to 'bar: string'
b(a)
function c (param: { readonly foo: number | string, bar: number | string }) {
param.bar = String(param.foo)
}
// Error: property 'bar: string' is not assignable to 'bar: number | string'
c(a)
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
The issue names no file or test entry point. Start by reviewing how compiler options and assignability are handled, then compare the mutable array and object examples with the readonly cases. Done means a pedantic option rejects the unsafe mutable generalizations while allowing the readonly conversions described.
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