![](/img/trans.png)
[英]TypeScript: How do I narrow / write a guard for a complex conditional type?
[英]how do I create a narrow type based on an objects values
我正在從流程轉向打字稿,我遇到了一些我無法弄清楚該怎么做的事情。 在流程中,我有以下幾點:
const color = Object.freeze({
white: '#ffffff',
black: '#000000',
})
type PossibleColorValues = $Values<typeof color>
在這種情況下, PossibleColorValues
'#ffffff' | '#000000'
是'#ffffff' | '#000000'
'#ffffff' | '#000000'
打字稿中是否有與此等效的內容? 我嘗試了以下方法:
type PossibleColorValues = typeof color[keyof typeof color]
但在這種情況下, PossibleColorValues
值只是string
您對如何獲得對象中所有可能值的聯合有正確的想法。 typeof color[keyof typeof color]
應該可以解決問題。
問題是color
不保留當前定義的原始類型。 您需要說服編譯器保留您最初在對象文字中分配的字符串文字類型。
在尚未發布的 3.4 中,您可以使用as const
來讓編譯器知道您需要文字類型和只讀對象。 因此,這將在 3.4 中按預期工作(再次可能在本月發布 3.4 時):
const color = Object.freeze({
white: '#ffffff',
black: '#000000',
} as const)
type PossibleColorValues = typeof color[keyof typeof color]
同時,您可以使用函數讓編譯器推斷文字類型:
declare function withLiterals<
T extends Record<string, V>,
V extends string | boolean | number | symbol | null | undefined | Record<string, V>
>(input: T ): T;
const color = Object.freeze(withLiterals({
white: '#ffffff',
black: '#000000',
}));
type PossibleColorValues = typeof color[keyof typeof color]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.