Skip to content

In JS, type unioning of this-assignments has undesired behaviour #22792

Closed
@sandersn

Description

@sandersn
function A() {
  this.p = 0
}
A.prototype.m = function(x) {
  this.p = x
}
var a = new A()
a.p // p: any

Expected behavior:
a.p: number

Actual behavior:
a.p: any

This happens because we treat all assignments to the property as declarations and then union their types. And any | T | ... === any

But compare:

function A() {
  this.ps = []
  this.maybe = undefined
}
A.prototype.init = function(x) {
  this.ps = [1,2,3]
  this.maybe = 'just'
}
var a = new A()
a.ps // ps: number[]
a.maybe // maybe: string | undefined

When the initialiser in the constructor has an uninformative type, the unioning can result in a much better type, or at least a less bad type (any). But perhaps the fix here is to handle these uninformative initialisers differently.

Metadata

Metadata

Assignees

Labels

BugA bug in TypeScriptFixedA PR has been merged for this issue

Type

No type

Projects

No projects

Relationships

None yet

Development

No branches or pull requests

Issue actions