One of the challenges I am facing involves a function that takes an object as a parameter and returns another object, with one of its properties being the value of a key in the original object. When attempting to retrieve this value using obj[key] notation, I encounter an issue.
I understand that the key must be of the proper type in order to use it like this. I cannot simply use a string as the key if the interface does not have [key: string]: any. However, my key is a union of strings that were keys in the passed object, such as 'user' or 'name'.
interface Twitter<T> {
name: T;
user: T;
sex: T extends string ? boolean : string;
}
interface Facebook<T> {
appName: T;
whatever: T;
imjustanexample: T;
}
type TwFbObjKeys = keyof Twitter<string> | keyof Facebook<string>
The function in question looks like this:
public static getArrayOfObjects(
queryParameters: Twitter<string> | Facebook<string>,
) {
const keys = Object.keys(queryParameters) as TwFbObjKeys[];
return keys.map((paramId) => ({
paramId,
value: queryParameters[paramId],
}));
}
I expected that using paramId, which is of type 'name' | 'sex' | 'appName' | ..., as a key for an object containing these keys would not result in an error. Unfortunately, I receive the following error:
TS7053: Element implicitly has an 'any' type because expression of type 'name' | 'sex' | 'appName' | ... can't be used to index type Twitter | Facebook. Property 'name' does not exist on type Twitter | Facebook
This issue has consumed several hours of my time. Any suggestions on how to resolve it?