如何从以字符串传入的标签类型中获取对应属性类型?
解决HTML标签属性类型匹配问题
要实现传入的属性与对应HTML标签严格匹配,只需利用TypeScript内置的JSX.IntrinsicElements类型——它包含了所有标准HTML标签的属性定义。修改createElement函数如下:
import type { ElementType } from 'react'; export const createElement = <C extends keyof JSX.IntrinsicElements>(Component: C) => { return (props: JSX.IntrinsicElements[C]) => ( <Component {...props} /> ); }; const Some = () => { const Textarea = createElement("textarea"); const Input = createElement("input"); return ( <> {/* 此处会触发TypeScript错误:textarea标签不支持type属性 */} <Textarea placeholder={"123"} type={"color"}/> {/* input标签支持type="color",正常通过类型检查 */} <Input type={"color"} /> </> ) }
关键说明:
- 泛型
C extends keyof JSX.IntrinsicElements:约束传入的Component必须是合法的HTML标签名(如"textarea"、"input")。 props: JSX.IntrinsicElements[C]:直接复用TypeScript内置的对应标签属性类型,确保传入的props完全符合该标签的标准属性定义。- 改造后,给
Textarea传入type这类非法属性时,TypeScript会自动抛出类型错误,而合法属性则正常通过检查。
内容的提问来源于stack exchange,提问作者Desperado
相关产品推荐
相关产品推荐

