Typescript 如何基于对象值创建窄类型
我正在从flow过渡到typescript的过程中,遇到了一些我不知道该怎么做的事情。在flow中,我有以下几点:Typescript 如何基于对象值创建窄类型,typescript,Typescript,我正在从flow过渡到typescript的过程中,遇到了一些我不知道该怎么做的事情。在flow中,我有以下几点: const color = Object.freeze({ white: '#ffffff', black: '#000000', }) type PossibleColorValues = $Values<typeof color> type PossibleColorValues = typeof color[keyof typeof color] 但
const color = Object.freeze({
white: '#ffffff',
black: '#000000',
})
type PossibleColorValues = $Values<typeof color>
type PossibleColorValues = typeof color[keyof typeof color]
但是在这种情况下,
PossibleColorValues
只是string
您对如何获得对象中所有可能值的并集有正确的想法typeof color[keyof typeof color]
应该可以做到这一点
问题在于,color
没有保留当前定义的原始类型。您需要说服编译器保留最初在对象文本中指定的字符串文本类型
在3.4(尚未发布)中,您可以使用as const
让编译器知道您需要文本类型和只读对象。因此,这将如3.4中所预期的那样起作用(可能在本月发布3.4时再次出现):
同时,您可以使用函数让编译器推断文字类型:
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]
用文本声明函数<
T延续记录,
V扩展字符串|布尔|数字|符号| null |未定义|记录
>(输入:T):T;
const color=Object.freeze(带文字)({
白色:“#ffffff”,
黑色:“000000”,
}));
type PossibleColorValues=颜色的类型[颜色的类型]
您考虑过使用枚举吗?
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]