我对 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/