Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Typescript type for function calling another function, with same parameters

I’m sure this is easy, but I don’t seem to be able to find an answer (or maybe ask the right question!)

I have a library function (specifically, an i18n.translator from here: https://primitives.solidjs.community/package/i18n#static-dictionaries), which I want to wrap with another function to provide some fallback value based on other logic.

const translator = i18n.translator(dict);

const custom_translator = (path, args?): string => {
    const translation = translator(path, args);
    if (translation) { return translation };
    return "Some fallback";
}

How do I make the custom_translator parameters the same types as translator? (the i18n.translator does some complex type inference on the dict object, so path is not just a string!)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

There are multiple ways. One would utilize Parameters utility type, that returns all parameters from F. So, you write your function like this:

const custom_translator = (...args: Parameters<typeof translator>): string => {
    const translation = translator(...args);
    if (translation) { return translation };
    return "Some fallback";
}

You can also do something like this (but it’s less maintainable):

const custom_translator = (path: Parameters<typeof translator>[0], args?: Parameters<typeof translator>[1]): string => {
    const translation = translator(...args);
    if (translation) { return translation };
    return "Some fallback";
}

Another way, if you want to fully copy interface would be to assign type of translator to your variable, but if you do so, your return type also will be like one translator have, and I don’t think you want this.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading