TypeScript:在代理中定义动态属性

时间:2018-01-24 20:29:07

标签: javascript typescript proxy

我对watch

进行了以下调用
const watch = hp.watch({
  running: false,
  time: 0,
  start: Date.now()
})

低音观看只需运行new proxy(),然后设置一些属性并返回新创建的proxy类,没什么太花哨的。

export function watch(item: { [key: string]: any }): proxy
export function watch(key: string, value: any): proxy
export function watch(...args: any[]): proxy {
  let prox = new proxy()
  if (args.length == 2) {
    prox[args[0]] = args[1]
  } else if (args.length == 1 && args[0] instanceof Object) {
    for (let itm in args[0]) {
      !(itm in prox) && (prox[itm] = args[0][itm])
    }
  }
  return prox
}

然后我有一个如下所示的界面:

export interface proxy {
  [key: string]: any
}

这是proxy类,它基本上只是一个包装器。

namespace hp {
  export class proxy {
    public constructor() {
      return new Proxy(this, { /* Proxy stuff */})
    }
  }
}

在支持intellisense的编辑器中,如果我在输入running后可以建议timestartwatch.,那就太好了。

我认为我需要使用更高级的interface(或type)而不是我正在使用的那个。{我试过这个,但它不起作用:

export type watch<T> = {
  [A in keyof T]: T[A]
} 

export interface proxy {
  [key: string]: watch<any>
}

执行watch.time = 123时,我收到错误消息:

  

键入&#39;数字&#39;不能分配到&#39; watch&#39;。

并且在尝试获取值let a = watch.time时出现此错误:

  

算术运算的右侧必须是&#39;任何&#39;,&#39;数字&#39;或者枚举类型。

1 个答案:

答案 0 :(得分:1)

您想要将hp.watch()的签名更改为

export function watch<T>(item: T): proxy & T;
export function watch<K extends string, V>(key: K, value: V): proxy & Record<K, V>;
export function watch(...args: any[]): proxy {
  // impl
}

然后你告诉TypeScript该函数的输出都是proxy,并且具有与传入的内容相同的键和值类型。

希望有所帮助;祝你好运!