DEV Community

Discussion on: TypeScript: type vs interface

Collapse
 
michaeljota profile image
Michael De Abreu

In the new section, you wrote:

interface IClassyAnimal {
  new (name: string);
}

But it should be:

interface IClassyAnimal {
  new (name: string): this;
}
Collapse
 
stereobooster profile image
stereobooster • Edited

Doesn't seem to help typescriptlang.org/play/#code/JYOw... 🤔

interface IClassyAnimal {
  new (name: string): this;
}

class Parrot implements IClassyAnimal {
  name: string;
  constructor(name: string) {
    this.name = name;
  }
}

// Class 'Parrot' incorrectly implements interface 'IClassyAnimal'.
//   Type 'Parrot' provides no match for the signature 'new (name: string): this'.

I guess the only reasonable usage of new is this:

interface ComesFromString {
    name: string;
}

interface StringConstructable {
    new(n: string): ComesFromString;
}

class MadeFromString implements ComesFromString {
    constructor (public name: string) {
        console.log('ctor invoked');
    }
}

function makeObj(n: StringConstructable) {
    return new n('hello!');
}

code example from stackoverflow.com/questions/134070...

If you want to declare type of constructor you can do something like this:

declare class IClassyAnimal {
  constructor(props: string);
}

class Parrot implements IClassyAnimal {
  name: string;
  constructor(name: string) {
    this.name = name;
  }
}
Collapse
 
michaeljota profile image
Michael De Abreu

Yes. I wasn't unable to check it, but I was sure I did something like that. But according to the docs

typescriptlang.org/docs/handbook/i...

Seems like you are right. Constructors interfaces declarations are mostly effective as function arguments.

Thread Thread
 
stereobooster profile image
stereobooster

I don't know all the answers, I simply experimented to write this post. It also can happen I miss a lot of things, or there are bugs in TS or some small details which I miss. All ideas are more than welcome. (TypeScript documentation seems to lag behind actual behavior sometimes)