[英]In TypeScript, can I specify the type of object fields while still getting the literal key types inferred?
[英]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.