microsoft / microsoft/TypeScript

T.constructor should be of type T

Open
#3,841 103 comments 291 reactions 0 assignees View on GitHub
In Discussion Suggestion
Dominant language
Go
Stars
111k
Forks
14.3k
Avg merge
2d 4h
Merged PRs (30d)
132

Description

Given

``` typescript
class Example {
}
```

The current type of `Example.constructor` is `Function`, but I feel that it should be `typeof Example` instead. The use case for this is as follows:

I'd like to reference the current value of an overridden static property on the current class.

In TypeScript v1.5-beta, doing this requires:

``` typescript
class Example {
static someProperty = "Hello, world!";

constructor() {
// Output overloaded value of someProperty, if it is overloaded.
console.log(
(this.constructor).someProperty
);
}
}

class SubExample {
static someProperty = "Overloaded! Hello world!";

someMethod() {
console.log(
(this.constructor).someProperty
);
}
}
```

After this proposal, the above block could be shortened to:

``` typescript
class Example {
static someProperty = "Hello, world!";

constructor() {
// Output overloaded value of someProperty, if it is overloaded.
console.log(
this.constructor.someProperty
);
}
}

class SubExample {
static someProperty = "Overloaded! Hello world!";

someMethod() {
console.log(
this.constructor.someProperty
);
}
}
```

This removes a cast to the current class.

Contributor guide

Open the contributing guide

Research direction

Use the two class examples in the issue as the behavioral starting point, then trace the TypeScript type-checking rules for instance constructors and static members. Done means the proposed this.constructor accesses type-check without the casts shown, while preserving the intended behavior for subclasses.

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
Active
Clarity
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.