簡體   English   中英

TypeScript:在代理中定義動態屬性

[英]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.后建議runningtimestart會很好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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM