microsoft / microsoft/TypeScript

Pedantic: deny mutable type generalization

Open
#39,915 3 comments 9 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Awaiting More Feedback Suggestion
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

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

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

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.