Typescript为具有推断数值的对象文字创建键约束类型



假设我们有对象文字,如:

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  

如何约束第二个对象文字,使其具有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的对象文字中捕获类型,但又想将其约束为具有相同的属性,则可以使用函数

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

游乐场链接

最新更新