Description
Search Terms
type, this, constructor, TS2526
Suggestion
Currently, this code fails with A 'this' type is available only in a non-static member of a class or interface.ts(2526)
:
class MyClass {
private props: { baz: string };
constructor(props: this["props"]) {
this.props = props;
}
}
It would be awesome if this
could be supported in constructor arguments.
Use Cases
This is very useful for react components, as demonstrated in the following example.
More general, sometimes a class extends a generic base class which requires generic data for initialization. If the super class also wants to do some initialization, it needs to pass this generic argument down to its base class. As constructor arguments must be typed, the type of this generic argument must be explicitly stated in the super class.
In those cases, it is very practical to use this
to refer to a field of that base class that has the right type.
Examples
class MyComponent extends React.Component<{
title: string;
}> {
constructor(props: this["props"]) {
super(props);
// ...
}
}
Current Workarounds
class MyComponent extends React.Component<{
title: string;
}> {
constructor(props: MyComponent["props"]) {
super(props);
// ...
}
}
This only works if the base class declares a static props
member.
Also, it has the downside that you must write out the name of the current class. This obfuscates the fact that it refers itself.
Checklist
My suggestion meets these guidelines:
- This wouldn't be a breaking change in existing TypeScript/JavaScript code
- This wouldn't change the runtime behavior of existing JavaScript code
- This could be implemented without emitting different JS based on the types of the expressions
- This isn't a runtime feature (e.g. library functionality, non-ECMAScript syntax with JavaScript output, etc.)
- This feature would agree with the rest of TypeScript's Design Goals.