【发布时间】:2021-12-13 08:07:39
【问题描述】:
请帮我改正我的打字错误。
我想将类名注入到样式化的组件中。 我做了这个功能:
type IntrinsicElementsKeys = keyof { div: any, a: any } /* could be keyof JSX.IntrinsicElements */
export function elementWithClass(e: IntrinsicElementsKeys, customClassName: string) {
/* [2] if I don't force the type ts does not allow me to call se.attrs() */
const se = styled[e] as ThemedStyledFunction<typeof e, any>
const res = se.attrs(props => ({
className: customClassName + " " + (props.className || "")
}))``
/* [1] if I don't force "any" then I cannot use native props such as "href" */
return res as any;
}
我想摆脱 [1] 处的“任何”,但如果我这样做并按如下方式调用组件:
const Link = elementWithClass("a", "rick-roll")
const MyElement: React.FC<{ /* props */ }> = props => <Link href="http://rick-roll.com">rick</Link>
然后 TS 抱怨“href”是一个未知的道具。
所以我的问题是:如何修正我的打字错误?
注意 1:如果我删除 [2] 处的“as”,那么 TS 会抱怨
Each member of the union type '(<U, NewA extends Partial<Pick<DetailedHTMLProps<HTMLAttributes<HTMLDivElement>, HTMLDivElement>, "key" | keyof HTMLAttributes<...>> & { ...; } & U> & { ...; } = {}>(attrs: Attrs<...>) => ThemedStyledFunction<...>) | (<U, NewA extends Partial<...> & { ...; } = {}>(attrs: Attrs<...>) => ThemedStyledFunction<...>)' has signatures, but none of those signatures are compatible with each other.
注2:这个问题类似于 use tailwind classes into styled-components 但更具体地说明了如何使用我使用的特定方法来修复打字。
【问题讨论】:
标签: reactjs typescript styled-components