microsoft/TypeScript

Class's prototype property is typed incorrectly and includes instance properties

Closed this issue ยท 4 comments

๐Ÿ”Ž Search Terms

class prototype typeof instanceof

๐Ÿ•— Version & Regression Information

  • This is the behavior in every version I tried, and I reviewed the FAQ for entries about all Common "Bugs" That Aren't Bugs

โฏ Playground Link

https://www.typescriptlang.org/play?target=9#code/MYGwhgzhAECC0G8BQ1oDMD2HoF5oCYBuFaAIzACcAKASkWgoFMAXAVwoDtoBGQ6AXySCkwDBwgYQjAHQgMAcyqxpABwoZmGgJ4qZmDABpoAcn3HoASy7K1G7bprFR4yTLmKb6zcx0zyFI2N-cys4VS97RkckIA

๐Ÿ’ป Code

class A {
  foo = 2;
  bar() { return 1; }
}

console.log(A.prototype.foo, 'foo' in A.prototype);
console.log(A.prototype.bar, 'bar' in A.prototype);

๐Ÿ™ Actual behavior

The type of A.prototype includes foo, which is an instance field and not actually present on the prototype.

๐Ÿ™‚ Expected behavior

The type of A.prototype should not include instance fields like foo.

Additional information about the issue

My motivation for looking into was trying to write a utility type that differentiated between instance properties and prototype properties in order to generate proper React props types from a class that ignored things that should not be set from the prototype. Right now there is no way at the type level to tell a field from a prototype method at all that I can see.

I believe this is essentially due to the lack of #9726.

I don't think this should be modelled as an enumerable properties issue. It's more that the instance type of a class is a union (or more accurately an extends type operation) of the instance properties with the prototype's type, but instead the prototype is typed the same as the instance type.

This issue has been marked as "Duplicate" and has seen no recent activity. It has been automatically closed for house-keeping purposes.