No way to type an object with null prototype
See original GitHub issueCurrently the base type of all objects in TS seems to be {}
, which looks like an empty type but actually has members inherited from the Object object. This leaves no way to express a type with null prototype.
var foo: ??? = Object.create(null);
foo.toString(); // Want a compile error here
I did accidentally discover that it’s possible to type a variable as void:
var foo: void = Object.create(null);
This appears to suppress intellisense for members in VS and the playground, and it is assignable to any
(Object.keys(foo)
compiles), so it would seem to be what I’m looking for. However this still lets foo.toString()
compile somehow - I imagine the void type is getting elevated to Object automatically.
Edit: Ryan’s workaround to subtype Object and override all its members to void prevents those properties from being called as functions, but as he points out, that doesn’t prevent them from being accessed.
var bar = foo.toString; // Want a compiler error here too. Won't get one with Ryan's workaround.
Issue Analytics
- State:
- Created 9 years ago
- Reactions:23
- Comments:19 (14 by maintainers)
Top GitHub Comments
If i’m looking to create a large inheritance structure, I prefer them to start on a null-prototype, It inherently protects them from possible prototype polution on the Object.prototype and as I basically never need to support the legacy Object.prototype methods, there is no real downside.
The lack of a proper Null object type in TS has made me use it less, and i dislike that.
@mhegazy @RyanCavanaugh what would you think about just changing
lib.d.ts
like below?Playground