簡體   English   中英

從具有類型 Boolean 屬性的 object 構建類型?

[英]Building a Type from an object with properties of type Boolean?

我想從這個 object 構造一個類型:

const isSynchronized: Record<SynchronizableField, boolean> = {
    /* synchronized */
    surveyMacroEnvironments: true,
    coordinateReferenceSystemCrs: true,
    transactionType: true,
    epsgTransformation: true,
    startingAgreementDate: true,
    expirationAgreementDate: true,
    transactionTypeNotes: true,
    surveyDataType: true,
    /* not synchronized */
    surveyName: false,
    validationStateCd: false,
    legacy: false,
    notifyOnCreate: false,
    notifyOnValidate: false,
    finalReportLink: false,
    // timestamp fields
    creationDate: false,
    lastUpdate: false,
    // continent and country are handled differently
    continent: false,
    country: false,
};

其中類型只需要具有值等於 true 的鍵,你能幫助我或給我任何建議嗎?

謝謝

作為第一步,我們必須刪除isSynchronized上的類型注釋 我們需要編譯器推斷其類型,然后使用該推斷類型來計算您要查找的鍵集。 您可以改用satisfies運算符來確保檢查屬性類型並將其限制為boolean

const isSynchronized = {
    surveyMacroEnvironments: true,
    coordinateReferenceSystemCrs: true,
    transactionType: true,
    epsgTransformation: true,
    startingAgreementDate: true,
    // ✂ ⋯ ✂
    lastUpdate: false,
    continent: false,
    country: false,
} satisfies Record<string, boolean>;

type IsSynchronized = typeof isSynchronized;

現在您可以檢查IsSynchronized以獲得所需的類型。


您正在尋找類型為 function 的應用程序,我將其稱為KeysMatching<T, V> ,如microsoft/TypeScript#48992中所要求的以及在 TypeScript 中所討論的,如何獲取值為給定的 object 類型的鍵類型? . 這個想法是KeysMatching<T, V>將評估T的屬性鍵的並集,其中這些鍵的屬性值可分配給V 具體來說,您似乎想要KeysMatching<IsSynchronized, true>

該語言不提供本機KeysMatching ,但有多種方法可以自行實現,但存在各種問題和邊緣情況。 一種方法是分布式 object 類型,其中我們對T的所有屬性進行 map ,然后使用所有鍵對結果進行索引,以計算屬性類型的並集結束。 像這樣:

type KeysMatching<T, V> =
    { [K in keyof T]: T[K] extends V ? K : never }[keyof T]

讓我們使用它:

type SynchronizedKeys = KeysMatching<IsSynchronized, true>;
// type SynchronizedKeys = "surveyMacroEnvironments" | "coordinateReferenceSystemCrs" |
//   "transactionType" | "epsgTransformation" | "startingAgreementDate" | 
//   "expirationAgreementDate" | "transactionTypeNotes" | "surveyDataType"

看起來不錯。 如果您不想保留KeysMatching ,您可以內聯定義以直接計算SynchronizedKeys

type SynchronizedKeys = {
    [K in keyof IsSynchronized]: IsSynchronized[K] extends true ? K : never
}[keyof IsSynchronized];

游樂場代碼鏈接

暫無
暫無

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

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