簡體   English   中英

Typescript 為具有推斷數值的 object 文字創建鍵約束類型

[英]Typescript create key constrained type for object literal with inferred number values

假設我們有 object 文字,如:

export const SOURCE = {
    UNKNOWN: 'Unknown',
    WEB: 'Web',
    MOBILE: 'Mobile',
    ...
} as const;

export const OTHER_SOURCE = {
    UNKNOWN: 0,
    WEB: 1,
    MOBILE: 2, // values might be not sequential or incrementing at all 
    ...
} as const;
OTHER_SOURCE.UNKNOWN // inferred to 0  

如何約束第二個 object 文字,使其具有來自SOURCE的鍵,但值仍被推斷為文字,而不是如下數字:

type ConstraintType = {
    [key in keyof typeof USER_SOURCE]: number; // how to infer (and possibly still force numbers) numeric values from the second object?
};
export const OTHER_SOURCE: ConstraintType = { ... } as const;
OTHER_SOURCE.UNKNOWN // inferred to number ]  

感謝您的幫助和澄清。

如果你指定一個變量的類型,也就是它的最終類型,所以只要右邊的表達式可以賦值給它,一切都很好。

如果要從分配給OTHER_SOURCE的 object 文字中捕獲類型,但還要將其限制為具有相同的屬性,則可以使用 function

export const SOURCE = {
    UNKNOWN: 'Unknown',
    WEB: 'Web',
    MOBILE: 'Mobile',
} as const;

function makeSource<T extends Record<keyof typeof SOURCE, V>, V extends number>(o: T): Readonly<T> {
  return o
}
const OTHER_SOURCE = makeSource( {
    UNKNOWN: 0,
    WEB: 1,
    MOBILE: 2, // values might be not sequential or incrementing at all  
});


OTHER_SOURCE.UNKNOWN // 1

游樂場鏈接

暫無
暫無

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

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