1

I define generic interface with constructor, then implement it but have an error 'TS2420 Type Resetter provides no match for the signature new (defaultValue: (...args: any[]) => T): IResetter<T>'

interface IResetter<T> {
    new (defaultValue: (...args: any[]) => T): IResetter<T>;
    get (): T;
    set (customValue: T);
    reset ();
}

class Resetter<T> implements IResetter<T> {

    private customValue: T = null;

    constructor (private defaultValue: (...args: any[]) => T) { }

    public get () {
        return this.customValue || this.defaultValue(arguments);
    }

    public set (customValue) {
        this.customValue = customValue;
    }

    public reset () {
        this.customValue = null;
    }

}

I don't understand what I did wrong.

1 Answer 1

2

The constructor signature is not part of the class instance type it is part of the 'static' side of a class. You can't force a class to implement a specific constructor by implementing an interface. You can create an interface for the static side of the class and when the class is assigned to that interface we will have an error:

interface IResetter<T> {
    get (): T;
    set (customValue: T): void;
    reset (): void;
}
interface IResetterConstructor {
  new <T>(defaultValue: (...args: any[]) => T): IResetter<T>;
}

class Resetter<T> implements IResetter<T> {

    private customValue: T | null = null;

    constructor (private defaultValue: (...args: any[]) => T) { }

    public get () {
        return this.customValue || this.defaultValue(arguments);
    }

    public set (customValue: T) {
        this.customValue = customValue;
    }

    public reset () {
        this.customValue = null;
    }

}

function createNumberResetter(ctor: IResetterConstructor) {
  return new ctor(() => 1);
}

createNumberResetter(Resetter) //ok
createNumberResetter(class { }) //err ctor not ok 

Play

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.