microsoft / microsoft/TypeScript

No way to type an object with null prototype

Open
#1,108 24 comments 42 reactions 0 assignees View on GitHub
Needs Proposal Suggestion
Dominant language
Go
Stars
111k
Forks
14.3k
Avg merge
2d 4h
Merged PRs (30d)
132

Description

Currently 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.

``` javascript
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:

``` javascript
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](https://github.com/Microsoft/TypeScript/issues/1108#issuecomment-62406685) 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.

``` javascript
var bar = foo.toString; // Want a compiler error here too. Won't get one with Ryan's workaround.
```

Contributor guide

Open the contributing guide

Research direction

Reproduce the Object.create(null) examples in the TypeScript playground, then trace how {}, void, and Object members are modeled. Done means a supported type can represent a null-prototype object and rejects both member-access examples. The issue does not name a file or test to target.

Written by the indexing model from the issue text.

Assessment

Tech stack
javascript, typescript
Domain
compilers
Issue type
Feature
Difficulty
5/5
Estimated time
Over a week
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
25/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.