簡體   English   中英

如何在 TypeScript 中獲取接口屬性的類型?

[英]How to get the type of an interface property in TypeScript?

所以我有一個類似的代碼:

interface MyInterface{
  a:any,
  b:string,
  c:boolean,
  d:number,
  readonly valueChanges:Subject<{key: keyof MyInterface, value: ???}>
}

我不知道如何在正確的“鍵”下寫入值的類型。 我已經嘗試了typeof MyInterface[key]但這可能不是解決它的方法。 :(

提前感謝您的時間!

您可以使用由Titian Cernicova-Dragomir發布的AllValues實用程序類型。 請注意,您不需要extends Record<PropertyKey, PropertyKey>因為它特定於反轉問題。

type AllValues<T> = {
    [P in keyof T]: { key: P, value: T[P] }
}[keyof T]

然后將此類型應用於您的界面,但請確保{key: valueChanges...}不是您的選項之一。

type KeyValueObject = AllValues<Omit<MyInterface, "valueChanges">>
interface MyInterface{
  a: any;
  b: string;
  c: boolean;
  d: number;
  readonly valueChanges: Subject<AllValues<Omit<MyInterface, "valueChanges">>>;
}

我不喜歡這里的循環引用,所以我個人會將它分解成可組合的部分。 MyInterface最終會成為一個type而不是一個interface ,但實際上幾乎沒有區別。

interface BaseInterface {
  a: any;
  b: string;
  c: boolean;
  d: number;
}

type WithValueChanges<T> = T & {
    readonly valueChanges: Subject<AllValues<T>>
}

type MyInterface = WithValueChanges<BaseInterface>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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