TypeScript:断言对象字面量具有彼此相等的键值

M.K*_*afi 4 typescript

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

换句话说:

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

// Bad
const testIds: KeyEqualsValue = {
  foo: 'bar' // Error
} as const
Run Code Online (Sandbox Code Playgroud)

Tit*_*mir 6

不是单一类型,你可以用一个函数来完成:

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

const testIds2 = propAsValue({
    foo: 'bar'
});
Run Code Online (Sandbox Code Playgroud)

游乐场链接

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

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

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