I've been working on creating a TypeScript helper for React's useState
hook. The goal is to simplify components' (functions) arguments/props like the following:
import { type Dispatch, type SetStateAction } from 'react';
export const ComponentOne = ({ clicked: boolean; setClicked: Dispatch<SetStateAction<boolean>> })
It can be quite cumbersome to repeat this code, so I came up with a builder type:
export type Name<N extends string> = `set${Capitalize<N>}`;
export type Builder<N extends string, S> = {
[key in N]: S;
} & {
[key in Name<N>]: S;
};
After tweaking the code a bit:
export type Props = {
className: string;
} & SetStateBuilder<'clicked', boolean>;
export const ComponentOne = ({ className, clicked, setClicked}: Props)...
It works, but the issue is that TypeScript is displaying them separately:
type Props = {
className: string;
} & {
clicked: boolean;
} & {
setClicked: boolean;
}
This is not ideal! I would like to combine clicked
and setClicked
together. The keys from Props
are fine as they are.
However, when I try to include [key in N]: S;
and [key in Name<N>]: S;
inside the Builder
, TypeScript sees them as the same and removes one.
Any assistance would be greatly appreciated.