typescriptinterfacetype-declaration

declaring return type for an arrow functions with dynamic parameters


i have an arrow function with dynamic parameters like

let user_data: any = {
    parameters: ["user_name", "status"],
    validate: (user_name: string, status: boolean) => {
        if (user_name && status) {
            return true;
        }
        return false
    },
    user_name: "name-1",
    status: false
}

let parameter_values: any[] = [];
for (let key_name of user_data["parameters"]) {
    parameter_values.push(user_data[key_name])
}
let valid_user = user_data["validate"](...parameter_values)

same function with single parameter

let user_data: any = {
    parameters: ["status"],
    validate: (status: boolean) => {
        return status ?? false
    },
    user_name: "name-2",
    status: false
}

let parameter_values: any[] = [];
for (let key_name of user_data["parameters"]) {
    parameter_values.push(user_data[key_name])
}
let valid_user = user_data["validate"](...parameter_values)

and some times it can be

let user_data: any = {
    parameters: [],
    validate: () => {
        return true
    },
    user_name: "name-3"
}

now i have to declare return type for the function in the interface and whatever the input my return type must be boolean, my interface look like

export interface UserData {
    parameters: string[],
    validate: Function, //should be function with return type boolean
    user_name: string,
    status?: boolean,
    [k: string]: any
}

i have searched for this but i found return type only for static parameters like this

interface Example {
    foo: () => string;
    bar(): string;
}

Solution

  • You can use a rest parameter in your interface declaration like this:

    interface Foo {
        validate(...a_args: unknown[]): boolean;
    }
    

    This works for the following:

    const foo1: Foo = {
        validate(){ return true; }
    }
    
    const foo2: Foo = {
        validate(a_status: boolean){ return a_status ?? false; }
    }
    
    const foo3: Foo = {
        validate(a_username: string, a_status: boolean){ return a_status && !!a_username; }
    }
    

    Playground