I read a lot, and found similar things but not exactly what I want.
I want to define a type by using a prop value inside an object and use that information to define other property inside this object.
JSX.IntrinsicElements includes definitions for all react elements. let's focus on the SVG elements circle and path for this example.
so lets try define the type defention:
export type svgCustomType<T extends "path" | "circle"> = {
svgElem: T;
svgProps?: { [key in keyof JSX.IntrinsicElements[T]]: JSX.IntrinsicElements[T] };
};
here I try to get the type value T(which can be "path" or "circle") and use this value to define the appropriate properties type for svgProps.(can be React.SVGProps<SVGCircleElement> or React.SVGProps<SVGPathElement>
example usage:
const test: svgCustomType = { //Error: "Generic type 'svgCustomType' requires 1 type argument(s)", why?
svgElem: "path",
svgProps: {
cx: 10, // next step: should be error here because cx is not defined in `SVGPathElement`
},
};
Why do I get Generic type 'svgCustomType' requires 1 type argument(s)? I want to get this type from svgElem value.
i will just mention that using const test: svgCustomType<"path"> = {...} will work and cx will not be accepted.
for clearly:
I'm not sure if is even possible in typescript.
I'm writing a react lib and i want my user to be able to get IntelliSense suggestions while typing,and if the user running typescript(and not javascript) he will also will get type errors.
let's say my lib component have prop svgHeadProp with type svgCustomType.
so i want the user to be able to write:
svgHeadProp={svgElem:"path",svgProps:{...}}
and not:
svgHeadProp<"path">={svgElem:"path",svgProps:{...}}
because not all my users uses typescript(and for the ones that does, its annoying specifying type for a prop )
cx, asReact.SVGProps<SVGPathElement>does have acxproperty for some reason (tsplay.dev/WoqolN).svgCustomType<"path">is that because of thesvgPropstyping, you need to usesvgProps: {cx: {cx: 10}}, which is accepted for both paths and circles.)