KraXen72
KraXen72
SSolidJS
Created by KraXen72 on 9/24/2023 in #support
better way to type props with default props
import { mergeProps, type JSX } from "solid-js";

// helper type which creates props type from defaultprops + adds children
// this would be somewhere in global.d.ts or imported.
type p<T extends Record<string, unknown>> = Partial<T> & { children?: JSX.Element; }

const defaultProps = {
message: "fallback message",
};

export default function Card(_props: p<typeof defaultProps>) {
const props = mergeProps(defaultProps, _props);
return <div>{props.children ?? props.message}</div>;
}
import { mergeProps, type JSX } from "solid-js";

// helper type which creates props type from defaultprops + adds children
// this would be somewhere in global.d.ts or imported.
type p<T extends Record<string, unknown>> = Partial<T> & { children?: JSX.Element; }

const defaultProps = {
message: "fallback message",
};

export default function Card(_props: p<typeof defaultProps>) {
const props = mergeProps(defaultProps, _props);
return <div>{props.children ?? props.message}</div>;
}
this is what i've come up with so far. is there a simpler/better way to type it? - the props should be optional, since i'm defining defaults for it - it should include optional children, since that's a special prop - i don't want a separate prop type for each component. - it should account for the fact that there can be additional props (thus the record string extension) - is this not a good idea? let me know! this works but, maybe i'm missing some obvious way to do it better. if this is really the general way it should be typed (like solid does not have some helper types for the pretty common scenario of default props), atleast i'd like to get rid of the typeof if possible, and move that to the helper type.
10 replies