ReactとTypeScriptにStyledComponentを使って見出し用のコンポーネントをつくりas
にh1〜h6までの要素を渡せるようにしたい
<Title as={props.sectionLevel || "h2"}>{props.title}</Title>
このとき、sectionLevel
をstringにしていたら、型チェックエラーがでた
TS2769: No overload matches this call. Overload 1 of 2, '(props: Omit<Omit<Pick<DetailedHTMLProps<HTMLAttributes
, HTMLHeadingElement>, "key" | keyof HTMLAttributes<...>> & { ...; }, never> & Partial<...>, "theme"> & { ...; } & { ...; }): ReactElement<...>', gave the following error. Type 'string' is not assignable to type 'undefined'. Overload 2 of 2, '(props: StyledComponentPropsWithAs , any, {}, never>): ReactElement<StyledComponentPropsWithAs<...>, string | JSXElementConstructor<...>>', gave the following error. Type 'string' is not assignable to type 'keyof IntrinsicElements | ComponentType | undefined'. index.d.ts(158, 53): The expected type comes from property 'as' which is declared here on type 'IntrinsicAttributes & Omit<Omit<Pick<DetailedHTMLProps<HTMLAttributes , HTMLHeadingElement>, "key" | keyof HTMLAttributes<...>> & { ...; }, never> & Partial<...>, "theme"> & { ...; } & { ...; }' index.d.ts(78, 42): The expected type comes from property 'as' which is declared here on type 'IntrinsicAttributes & StyledComponentPropsWithAs , any, {}, never>'
この情報からどう型をつけるべきか読み取れなかったので調べたら
emotionのissueだが、似たような質問が書いてあって github.com
結果的にStyledComponentでもReact.ElementType
にしたらエラーが解消された