打字稿为具有推断数值的对象文字创建键约束类型
Typescript create key constrained type for object literal with inferred number values
假设我们有像这样的对象字面量:
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
假设我们有像这样的对象字面量:
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