简体   繁体   English

创建一个类型为 object 的函数

[英]Creating a type that is an object of functions

I have some methods in TypeScript that are passed functions like getJson .我在 TypeScript 中有一些方法,它们传递了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 .在应用程序中,这是一个实际的getJson function ,它符合它的含义,但出于测试目的, getJson使用与原始getJson形状相同的 function 进行模拟。

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.这很好用,但我有很多依赖项,可能需要添加更多,并且输入 function 名称然后再次键入typeof -function- -function- 有很多冗余。

Is there any way to create the type that is an object with keys that match the function names whose values are the functions?有什么方法可以创建类型为 object 的类型,其键与值是函数的 function 名称匹配?

You can use typeof on the whole object, and typescript will do the work for you:您可以在整个 object 上使用typeof ,typescript 将为您完成工作:

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现在 MyObjectType 是

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.您可以将该类型应用于任何其他 object。

TS Playground TS游乐场

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM