I have a StringToString interface, which I use all over the place:
interface StringToString {
[key: string]: string;
}
I also exchange the key and values in my objects quite regularly. This means that the keys become values, and the values become keys. This is the type signature for the function.
function inverse(o: StringToString): StringToString;
Now here's the problem: Since this exchange is done quite often, I'd like to know if the object I'm treating has keys as values or keys as keys.
This means I'd like two types:
export interface KeyToValue {
[key: string]: string;
}
export interface ValueToKey {
[value: string]: string;
}
type StringToString = KeyToValue | ValueToKey;
With these, the inverse
function becomes:
/** 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
}
Now I'd like typescript to show errors when I'm assigning to ValueToKey
to KeyToValue
. Which means I'd like this to throw an error:
function foo(obj: KeyToValue) { /* ... */ }
const bar: ValueToKey = { /* ... */ };
foo(bar) // <-- THIS SHOULD throw an error
Is that possible?