M.K. Safi
M.K. Safi

Reputation: 7039

TypeScript: assert an object literal has key-values that equal each other

Is it possible in TypeScript to assert that a const object literal is made in such a way where each key equals its value?

In other words:

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

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

Upvotes: 6

Views: 1692

Answers (2)

Titian Cernicova-Dragomir
Titian Cernicova-Dragomir

Reputation: 250156

Not with a single type, you can do it with a function:

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

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

Playground Link

Or with an inline function, if you want to be terse and confuse everyone:

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

Although I am not sure what your use case for this is, you might be better off with using Object.keys.

Upvotes: 7

Codyj110
Codyj110

Reputation: 578

Yes you can get the object keys with Object.keys then you can loop through the keys and compare the string values. If they do not equal you can throw an error.

Upvotes: 0

Related Questions