首页 > 解决方案 > TypeScript:断言对象文字具有彼此相等的键值

问题描述

在 TypeScript 中是否可以断言const对象文字是以每个键等于其值的方式制作的?

换句话说:

// Good
const testIds: KeyEqualsValue = {
  foo: 'foo'
} as const

// Bad
const testIds: KeyEqualsValue = {
  foo: 'bar' // Error
} as const

标签: typescript

解决方案


不是单一类型,你可以用一个函数来做到这一点:

function propAsValue<T extends { [P in keyof T]: P }>(o: T) {
    return o;
}
const testIds = propAsValue({
    foo: 'foo'
});

const testIds2 = propAsValue({
    foo: 'bar'
});

游乐场链接

或者使用内联函数,如果你想简洁并让每个人都感到困惑:

const testIds = (<T extends { [P in keyof T]: P }>(o: T) => o)({
    foo: 'foo'
});

尽管我不确定您的用例是什么,但使用Object.keys.


推荐阅读