ARTICLE AD BOX
I have the interface of a React component that looks like this:
interface SomeReactComponentProps<Resource> { resources: Resource[]; selectName: (resource: Resource) => string; }The selectName callback is used to define the specific name property of the resource, which might be resource1.name, resource2.foo, resource3.bar, etc.
I now want the type of the resources to be a partial of the Resource-generic, that at least contains the identified name-property from the selectName-function plus (optionally) any additional properties of the generic.
Does anyone have an idea how to do this in TypeScript, so that I get type safety for the resources depending on the selectName-function?
Edit: Minimal reproducible example:
import React from 'react'; type SomeReactComponentProps<Resource> = { [K in string & keyof Resource]: { allResources: (Partial<Resource> & Pick<Resource, K>)[] | undefined; selectName?: (resource: Resource) => K; }; }[string & keyof Resource]; function SomeReactComponent<Resource>({ allResources, selectName, }: SomeReactComponentProps<Resource>): React.ReactElement { return <OtherReactComponent allResources={allResources} selectName={selectName} />; } function OtherReactComponent<Resource>({ allResources, selectName, }: SomeReactComponentProps<Resource>): React.ReactElement { return <ul>{selectName && allResources?.map((resource) => <li>{selectName(resource)}</li>)}</ul>; } export { SomeReactComponent, SomeReactComponentProps };