Home > database >  How to create method that take the keyof interface as an argument, and the arguments of the function
How to create method that take the keyof interface as an argument, and the arguments of the function

Time:07-28

the title seems too long but sees my example.

I have this interface

interface Types {
    string: (value: string, letterAllowed: string[]) => boolean;
    number: (value: number, maxNumber: number) => boolean;
}

and this object which uses the interface

const types: Types = {
    string: (value: string) => typeof value === "string",
    number: (value: number) => typeof value === "number",
};

and i have this class with this interface

interface Check {
    test(type: keyof Types, ...args: any): boolean;
}

class Check {
    value: any;

    constructor(value: any) {
        this.value = value;
    }

    test(type, ...args) {
        return types[type](this.value, args);
    }
}

what I want is this.

// show error, you need to pass key of "Types"
new Check("value").test("");

// show error, you need to pass the maxNumber argument
new Check(5).test("number");
// no errors
new Check(5).test("number", 10);

// show error, you need to pass the letterAllowed argument
new Check("value").test("string");
// show error, letterAllowed is array of strings not number
new Check("value").test("string", [1, 2, 3]);
// no errors
new Check("value").test("string", ["a", "b", "c"]);

what I have tried so far is this.

interface Types {
    name: (value: string, letterAllowed: string[]) => string;
}

type ParametersExceptFirst<F> = F extends (arg0: any, ...rest: infer R) => any ? R : never;

interface Check {
    <K extends keyof Types>(value: K): Types[K];

    <K extends keyof Types>(value: K, ...args: ((R & ((arg0: any, ...rest: R[]) => any)) | never[])[]): boolean;
}

const check: Check = (value: any, ...args) => {
    return true;
};

// [✅] it shows an error if you don't pass any key of "Types"
check("");

// it doesn't show an error if you didn't pass the second argument
check("name");

// [✅] it shows an error if you pass an array of different types instead of a string
check("name", [1, 2, 3]);

what I want is how can I improve what I build and use it with a class method

Edit

  • Related