Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prevent constructor method misspelling

One of the most common ES6-specific mistakes I've encountered is misspelled constructor method.

Obviously, this won't have any effect, because a class has default constructor method:

interface IConstructor {
    constructor: Function;
}

class Foo implements IConstructor {
  contructor() { ... }
}

How can this problem be addressed with TypeScript, preferably at compilation time?

like image 963
Estus Flask Avatar asked Apr 10 '26 17:04

Estus Flask


2 Answers

The best way to safeguard against this and save on typing is to use a snippet in your text editor to create a constructor.

For example, in my editor I just type in ctor then hit tab and it creates a default constructor for me. You'll have to look up how to do this in whatever editor your using. Most editors support snippets (if not, you should switch editors).

Writing extra code just to prevent this problem is overkill for sure.

like image 95
David Sherret Avatar answered Apr 12 '26 08:04

David Sherret


You can't safeguard against it, not easily.

You can work around it, for example:

class Base {
    protected constructor() {}
}

class A extends Base {
    contructor() { }
}

let a = new A(); // error: Constructor of class 'Base' is protected and only accessible within the class declaration

(code in playground)

But that's far from being ideal.

like image 40
Nitzan Tomer Avatar answered Apr 12 '26 08:04

Nitzan Tomer



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!