【问题标题】:Is there a way to describe type for Proxy based on modified properties in typescript有没有办法根据打字稿中的修改属性来描述代理的类型
【发布时间】:2021-12-26 21:09:18
【问题描述】:

我有一个路线列表:

export interface RouteMap {
  routeA: string;
  routeB: string;
  routeC: string;
  ...
}

const routesMap: RouteMap = {
  routeA: 'route-a-url',
  routeB: 'route-b-url/:param',
  routeC: 'route-c-url/:some-id/data',
  
  ...
}

还有一个Proxy 指向可以处理方法的对象:

  • getRouteNameUrl(...arg: any[]): string;
  • goToRouteNameUrl(...arg: any[]): void;
  • 可能是其他一些动态样板文件

即getRouteAUrl、getRouteBUrl 等。

问题是:

有没有一种方法来描述 Proxed 对象,即基于 typescript 中某些接口/类类型的 修改 属性?

类似的东西

type ProxedRouteMap<T> = {
  [get`[P in keyof T]`Url]: (...arg: string[]) => string;
  [goTo`[P in keyof T]`]: (...arg: string[]) => void;
  ...
}

const routeMapService: ProxedRouteMap<RouteMap> = new Proxy(routeMap, {
  apply(target, thisArg, ...args) {
    ...
  }
});

【问题讨论】:

  • this approach 是否满足您的需求?如果是这样,我可以写一个答案;如果不是,请解释任何不满意的用例。
  • @jcalz 谢谢,这是非常好的解决方案,可能也应该添加为答案。

标签: typescript es6-proxy


【解决方案1】:

是的,您可以在mapped type 中使用as 子句,通过它可以指定生成的属性名称的转换:

type ProxedRouteMap<T> = {
  [P in keyof T as `get${Capitalize<string & P>}Url`]: (...arg: string[]) => string;
} & {
  [P in keyof T as `goTo${Capitalize<string & P>}`]: (...arg: string[]) => void;
}

/**
 * {
 *  getRouteAUrl: (...arg: string[]) => string;
 *  getRouteBUrl: (...arg: string[]) => string;
 *  getRouteCUrl: (...arg: string[]) => string;
 * } & {
 *  goToRouteA: (...arg: string[]) => void;
 *  goToRouteB: (...arg: string[]) => void;
 *  goToRouteC: (...arg: string[]) => void;
 * } 
 */
type Foo = ProxedRouteMap<RouteMap>

Playground


甚至更简单:

type ProxedRouteMap<T> = {
  [P in `get${Capitalize<keyof T & string>}Url`]: (...arg: string[]) => string;
} & {
    [P in `goTo${Capitalize<keyof T & string>}`]: (...arg: string[]) => void;
  }

【讨论】:

    猜你喜欢
    • 2019-09-24
    • 2021-02-04
    • 2019-07-03
    • 1970-01-01
    • 1970-01-01
    • 2020-09-28
    • 1970-01-01
    • 2023-02-08
    • 1970-01-01
    相关资源
    最近更新 更多