I have a situation where I frequently use a StringToString interface:
interface StringToString {
[key: string]: string;
}
There are instances when I need to switch the keys and values in my objects. In this scenario, the keys become values and the values become keys. Here is the type signature for the function:
function inverse(o: StringToString): StringToString;
The issue arises from the fact that I often perform this key-value exchange and I want to determine if the object being manipulated has keys as values or keys as keys.
To address this requirement, I defined two types:
export interface KeyToValue {
[key: string]: string;
}
export interface ValueToKey {
[value: string]: string;
}
type StringToString = KeyToValue | ValueToKey;
This leads to a modified version of the inverse
function:
/** Inverses a given object: keys become values and values become keys. */
export function inverse(obj: KeyToValue): ValueToKey;
export function inverse(obj: ValueToKey): KeyToValue;
export function inverse(obj: StringToString): StringToString {
// Implementation
}
My goal now is to have TypeScript generate errors when attempting to assign ValueToKey
to KeyToValue
. For instance, this assignment should produce an error:
function foo(obj: KeyToValue) { /* ... */ }
const bar: ValueToKey = { /* ... */ };
foo(bar) // <-- THIS SHOULD throw an error
Is there a way to achieve this?