loading...

re: TypeScript: type vs interface VIEW POST

TOP OF THREAD FULL DISCUSSION
re: In the new section, you wrote: interface IClassyAnimal { new (name: string); } But it should be: interface IClassyAnimal { new (name:...
 

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;
  }
}
 

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.

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)

code of conduct - report abuse