TypeScript: typing constructor breaks
See original GitHub issueSometimes it is necessary to type the “constructor” prop of the instance of a class.
Prettier 1.11.1 Playground link
Input:
class A {
'constructor': typeof A
static Foo() {
return new A()
}
}
const a = new A()
a.constructor.Foo()
Output:
class A {
constructor: typeof A;
static Foo() {
return new A();
}
}
const a = new A();
a.constructor.Foo();
Expected behavior:
Quotes around constructor
should not be removed, as the current behavior leads to constructor implementation missing
and removing the type declaration leads to Foo
does not exist on type Function
in a.constructor.Foo()
See typescript playground for errors caused
Issue Analytics
- State:
- Created 6 years ago
- Reactions:3
- Comments:17 (17 by maintainers)
Top Results From Across the Web
Documentation - Classes - TypeScript
Constructor (MDN). Class constructors are very similar to functions. You can add parameters with type annotations, default values, and overloads:.
Read more >Constructor overload in TypeScript - Stack Overflow
When ran with tsc BoxSample.ts, it throws out a duplicate constructor definition -- which is obvious. Any help is appreciated. typescript · constructor...
Read more >TypeScript constructors and generic types - Simon Holywell
There are types for all the native JavaScript constructors such as Number , String , Function and Object .
Read more >Better Constructor Overloading In Typescript/Angular - Upmostly
Now adding and removing constructors does not break any other constructor, and they all act independently from one another. Related Posts: What ...
Read more >Google TypeScript Style Guide
Language Rules: Visibility: Constructors: Class Members: Primitive Types & Wrapper Classes: Array constructor: Type coercion: Variables: Exceptions ...
Read more >
Top Related Medium Post
No results found
Top Related StackOverflow Question
No results found
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free
Top Related Reddit Thread
No results found
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Dev.to Post
No results found
Top Related Hashnode Post
No results found
It seems in typescript
constructor
is a keyword, so it makes sense why the quotes are currently needed. It also makes sense that this could be a bug in typescript.That said, the spec for typescript is typescript, and we are converting valid typescript to invalid typescript.
If we follow the principle of least astonishment, then prettier shouldn’t break this.
But also, in the giant typescript code bases I work with, I have never seen a real need for the syntax presented by OP (not to say it isnt needed sometimes, but its probably a low percentage of code) and thus the work around might be acceptable.
In essence, I have helped not at all 😉
But we need a test for this to make sure it won’t break again. Reopening.