For a specific use-case, I am looking to conditionally add a key to an interface. In attempting to achieve this, I used the following code:
key: a extends b ? keyValue : never
However, this approach breaks when a
is generic and also necessitates explicit passing of 'never' as the value for the key.
The main questions here are how to make the generic aspect work and how to effectively "filter out" never types so that they don't have to be explicitly passed.
Typescript Playground with the above example
export type Component<T extends ComponentList> = {
id: T;
kids: GetProps<T> extends { children: Record<string, any> } ? string[] : never;
};
// Change Wrapper to Button and you will see that kidType changes between string[] and never like it is supposed to
// But as an argument to reComponent it always thinks that the kids option is never, and it also asks me to give it a never option ??
type WrapperProps = GetProps<"Wrapper">
type kidType = WrapperProps extends {children: Record<string, any> } ? string[] : never;
const reComponent = <T extends ComponentList>(arg0: Record<string, Component<T>>) => {};
reComponent({
button1: {id: "Button" },
wrapper1: {id: "Wrapper", kids: [""]},
});
var Wrapper = ({
children,
}: {
children: Component<'Wrapper'> | Component<'Button'>
}) => {
return "react.component"
};
var Button = ({
text,
}: {
text: string
}) => {
return 123
};
var Components = {
Wrapper,
Button,
};
export type ComponentList =
| 'Wrapper'
| 'Button'
export type GetProps<T extends ComponentList> = Parameters<typeof Components[T]>[0];