I can't figure out if what I'm trying to do is possible to do in Typescript.
I want to be able to infer certain properties from an object. Not the whole object itself. Let me give you an example.
Given this object:
export const widgetConfig: WidgetConfig = {
greeting: {
label: "Greeting",
value: "Hello",
},
showTitle: {
label: "Show Title",
value: true,
},
// ...
};
I need a type that looks like this:
{
greeting: string;
showTitle: boolean;
// ...
}
greeting comes from the key greeting in the widgetConfig. It's value type comes from the type of data stored within value. The same is reflected for the showTitle boolean. This way, I can utilize the type inside React component props:
const Example = (props: WidgetProps<typeof widgetConfig>) => {
return props.showTitle && <h1>{props.greeting} from example</h1>;
};
The current problem I have is that both showTitle and greeting on props has the type string | number | boolean | undefined. I just want a string type for the greeting and a boolean type for the showTitle props.
Here is what WidgetProps looks like:
export type Widget =
| BooleanWidget<boolean>
| CodeWidget<string>
| DateWidget<string>
| NumberWidget<number>
| SelectWidget<string>
| TextWidget<string>;
export type WidgetConfig = Record<string, Widget>;
export type WidgetProps<T extends WidgetConfig> = {
[K in keyof T]: T[K]["value"];
};
Any ideas how to auto-infer the types based off of the config?