Enum ResourceType contains various resource types such as Blog and BlogAuthor.
enum ResourceType {
Blog = "blogs",
BlogAuthor = "blog_authors",
[...]
}
An interface called ResourceDefinitions stores typings for all resource types:
interface ResourceDefinitions {
[ResourceType.Blog]: BlogResource;
[ResourceType.BlogAuthor]: BlogAuthorResource;
[...]
The goal is to ensure that resource
is typed as
BlogResource</code in the following code snippet:</p>
<pre><code>const resource = useResource(ResourceType.Blog, id);
The implementation of useResource
function is as follows:
const useResource = <P extends ResourceType, T = ResourceDefinitions[P]>(
type: P,
id: string
): T => {
[...]
};
However, using T = ResourceDefinitions[P]
results in error
TS2536: Type 'P' cannot be used to index type 'ResourceDefinitions'.
.
Is there a workaround for this issue?
Two possible solutions are provided below:
The first solution involves manually typing each instance like so:
const useResource = <T>(
type: ResourceType,
id: string
): T => {
[...]
};
const resource = useResource<BlogResource>(ResourceType.Blog, id);
The second solution utilizes the keyof operator to type the resourceType manually:
const useResource = <P extends keyof ResourceDefinitions, T = ResourceDefinitions[P]>(
type: P,
id: string
): T => {
[...]
};
const resource = useResource(ResourceType.Blog as keyof ResourceDefinitions, id);