[英]TypeScript: define dynamic properties in 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的编辑器中,如果我建议在输入watch.
后建议running
, time
, start
会很好watch.
。
我想我需要使用比我正在使用的interface
更高级的interface
(或type
)。 我已经尝试过了,但是没有用:
export type watch<T> = {
[A in keyof T]: T[A]
}
export interface proxy {
[key: string]: watch<any>
}
当执行watch.time = 123
,出现错误消息:
类型“数字”不可分配给类型“手表”。
当尝试获取值时, let a = watch.time
此错误:
算术运算的右侧必须为“ any”,“ number”或枚举类型。
您想将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
,又与您传递的东西具有相同的键和值类型。
希望能有所帮助; 祝好运!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.