【问题标题】:TypeScript: define dynamic properties in proxyTypeScript:在代理中定义动态属性
【发布时间】:2018-01-24 20:29:07
【问题描述】:

我有以下电话给watch

const watch = hp.watch({
  running: false,
  time: 0,
  start: Date.now()
})

watch 基本上只是运行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 */})
    }
  }
}

在支持智能感知的编辑器中,如果我能在我输入 watch. 后让它建议 runningtimestart,那就太好了。

我认为我需要使用更高级的interface(或type)来实现这一点。我已经尝试过了,但它不起作用:

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

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

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

类型 'number' 不能分配给类型 'watch'。

当尝试获取值 let a = watch.time 时,我收到此错误:

算术运算的右侧必须是“任意”、“数字”或枚举类型。

【问题讨论】:

  • hp.watch() 的类型签名是什么?大概你希望它看起来像watch&lt;T&gt;(obj: T): T &amp; hp.proxy,但没有更多信息我不确定这是否能解决它
  • @jcalz 我已经更新了我如何定义watch 的问题。也许我不应该将函数和类型命名相同?

标签: javascript typescript proxy


【解决方案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 并且具有与你传入的东西相同的键和值类型。

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

【讨论】:

    猜你喜欢
    • 2012-06-26
    • 2012-12-06
    • 2022-01-16
    • 2020-10-11
    • 1970-01-01
    • 2012-12-29
    • 1970-01-01
    • 1970-01-01
    • 2010-11-06
    相关资源
    最近更新 更多