用程序将方法添加到TypeScript中具有类型安全性的类中



我正在为web服务编写一个客户端,其中一个端点从可能的20个参数中获取一个参数(可能会增加(。

我在客户端上公开了每种可能性的方法。现在我是这样做的:

// keys.ts
export const FUNCTION_ONE = 'FunctionOne';
export const FUNCTION_TWO = 'FunctionTwo';
...
export const FUNCTION_TWENTY = 'FunctionTwenty';
// client.ts
import * as keys from './keys';
import { camelcase } from 'lodash';
export default class Client {
makeCall(method: string): Promise<void> {
// some implementation
}
}
Object.values(keys).forEach((key) => {
(Client.prototype as any)[camelcase(key)] = function () {
return this.makeCall(key);
};
});

Typescript对这些方法一无所知,因为它们是以编程方式添加的。我不想手动编写这些方法中的每一个,因为服务可能会添加更多,而且我希望将它们添加到keys.ts文件中更容易。

我正在考虑对键进行修改,这将要求我键入键的camelcase形式(一个可接受的折衷(,然后我可以使用它来构建一个可以与类组合的类型。类似这样的东西:

// keys.ts
function key<T extends string>(command: string, name: T) {
return { command, name };
}
export const FUNCTION_ONE = key('FunctionOne', 'functionOne');
...
// client.ts
export default class Client {
// same as before
}
interface ClientInterface<T extends Record<string, { name: string }>> {
// implementation??
}
export default type Client = ClientInterface<keys>;

我该如何编写ClientInterface类型,它生成一个将键中的所有名称作为方法的接口?或者有更好的方法完全做到这一点吗?

您可以使用:

type ClientInterface<T extends Record<string, { name: string }>> =
{[N in T[keyof T]["name"]]: () => Promise<void> };
export type ClientType = ClientInterface<typeof keys>;

或者,如果你愿意用camel大小写来命名你的常数,那么它会变得简单一点,并且常数上的"rename"命令将能够更新所有调用:

type ClientInterface<T> =
{[N in keyof T]: () => Promise<void> };
export type ClientType = ClientInterface<typeof keys>;

相关内容