0

I have some methods in TypeScript that are passed functions like getJson. In the application, this is an actual getJson function that does what it implies, but for testing purposes, getJson is mocked with a function that is the same shape as the original getJson.

I'm creating a type for these dependencies that currently looks like this:

import { getJson } from 'get-json';

interface Dependencies {
  getJson: typeof getJson;
  ... others ...
}

This works great, but I have quite a few dependencies and may need to add more, and there's a lot of redundancy with typing the function name and then typeof -function- again.

Is there any way to create the type that is an object with keys that match the function names whose values are the functions?

1
  • 1
    I don't think you'll be able to consistently identity the scope those functions are in in order to "look them up" this way. Instead, maybe make a dependencies object of the shape you are looking for, using shorthand property names... and then get that object's type.. like this, maybe. Commented May 6, 2021 at 15:28

1 Answer 1

1

You can use typeof on the whole object, and typescript will do the work for you:

const function1 = (x: string) => undefined;
const function2 = (x: number, y: boolean) => 5;
const function3 = () => ({x: true, y: 5});

const myObject = {
  function1, 
  function2, 
  function3
}

type MyObjectType = typeof myObject;

Now MyObjectType is

type MyObjectType = {
    function1: (x: string) => undefined;
    function2: (x: number, y: boolean) => number;
    function3: () => {
        x: boolean;
        y: number;
    };
}

And you can apply that type to any other object.

TS Playground

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.