1

I have class example:

export class Test{
    private func:  (...args: any[]) => void;
    constructor(func: (...args: any[]) => void) {
       this.func = func;
    }
    method(...args: any[]) {
        return this.func(...args);
    }
}

I want to not see TS warning that the arguments not in constructor, and i want to see TS warning that the method require "testFunction" function arguments.

Use example:

const testFunction = (a: number, b: string) => {}

const test = new Test(testFunction); // I want to not see TS warning that the arguments were not passed

test.method(1, 'e') // I want to see TS warning that the method require "testFunction" function arguments

1 Answer 1

3

You should be able to accomplish this with generics:

class Test<P extends any[], R> {

    constructor(
        private func: (...params: P) => R
    ) {
        // Defensive check
        if (typeof this.func !== 'function') {
            throw new Error("Initializer must be a function");
        }
    }

    method(...params: P): R {
        return this.func(...params);
    }

}

When creating a new Test instance, the generics will be inferrred:

// "test" is a Test<[number, number], number>
const test = new Test((a: number, b: number) => a + b);

And will inform the Typescript compiler:

test.method(5, 6);                 // ✅ Compiles
test.method(5, '6');               // ❌ Does not compile
test.method(42);                   // ❌ Does not compile
test.method(1, 2, 3);              // ❌ Does not compile

let n: number = test.method(5, 6); // ✅ Compiles
let s: string = test.method(5, 6); // ❌ Does not compile
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.