Consider two Typescript interfaces A and B:
interface A {
propertyA: string;
propertyB: string;
propertyC: string;
propertyD: string;
propertyE: string;
}
interface B {
propertyF: string;
propertyG: string;
propertyH: string;
propertyI: string;
propertyJ: string;
propertyK: string;
}
I want to define a constant, a Key-Value Pair, that pairs a string value with either interface A or interface B.
const keyValuePair: { [key: string]: A | B} = {};
Then, a function would pass in a generic value, T, indicative of what the value in the Key-Value Pair would be, and I would return the Key-Value Pair with the appropriate value object:
export async function getKeyValuePair<T>(keyId: string): Promise<T> {
if (keyValuePair<T>[keyId]) {
return keyValuePair<T>[keyId];
}
}
Obviously. The above will not work. But, how can I get it to work? If I was just doing interface A, I would do the following and it would work fine:
const keyValuePair: { [key: string]: A} = {};
export async function getKeyValuePair(keyId: string): Promise<A> {
if (keyValuePair[keyId]) {
return keyValuePair[keyId];
}
}
I realize I could do the following:
const keyValuePair: { [key: string]: any} = {};
But I really want something better and would like to avoid use of "any" if possible. How would I do this?
If you goal is to retrieve an object and cast it to a certain type you could do this:
export async function getKeyValuePair<T>(keyId: keyof T): Promise<T> {
return keyValuePair[keyId] as unknown as T;
}
So you could use like this:
getKeyValuePair<B>('propertyF');