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

标签 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 */})
    }
  }
}

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

我想我需要使用更高级的interface (或 type )比我正在使用的那个发生。我已经尝试过,但它不起作用:

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

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

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

Type 'number' is not assignable to type 'watch'.

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

The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type.

最佳答案

您想要将 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 该函数的输出既是一个代理,又具有与您传入的内容相同的键和值类型。

希望有帮助;祝你好运!

关于javascript - TypeScript:在代理中定义动态属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48431075/

相关文章:

mysql - 在带有日期的 Sequelize 中使用 Op.between 时出现 TypeScript 错误

javascript - 从平面对象数组构建对象树数组

url - 在 Go 中通过代理获取 URL 时出错

java - 为什么Java不支持socks4?

javascript - 构建当前小时时间戳的最快方法

javascript - addEventListener 中的 Event 对象如果没有传入回调,从哪里来?

Javascript - 将多个动态值添加到 for 循环中的动态键

angular - WebStorm:Angular 模板类型检查

firefox - 删除 Firefox 中保存的代理凭证

javascript - 如何获取进程nodejs的局部范围内的所有变量