【发布时间】:2021-01-20 07:18:20
【问题描述】:
是否可以有动态类型?我有一个这样的json
{
"fieldName": "Some text",
"type": String,
"inputType": "text"
},
{
"fieldName": "Some bool",
"type": Boolean,
"inputType": "checkbox
}
基于该 json,我想渲染像这样的字段组件
const Field: React.FC<FieldInterface> = ({ name, type, handler }) => {
const [value, setValue] = useState<type>()
const handleOnChane = (e: ChangeEvent<HTMLInputElement>) => {
setValue(e.target.value)
handler(name, e.target.value)
}
return (
<div>
<label htmlFor={name}>{name}</label>
<input
type={type}
id={name}
onChange={handleOnChane}
value={value}
></input>
</div>
)
}
export default Field
这是我的界面
export interface FormInterface {
fields: FieldPropInterface[]
submitAction: Function
}
export interface FieldPropInterface {
name: string
inputType: string
type: <Here I would like to have something but don't know what>
}
export interface FieldInterface {
name: string
type: string
handler: Function
}
你看,我需要那个类型来设置 useState 钩子变量的类型。 有可能吗?
回购链接: https://github.com/johnathan-codes/react-form-from-json
【问题讨论】:
-
你已经看过 typescript typeof 操作符了吗?
-
考虑阅读 typescript 文档。这是基础知识的基础。
-
@A_A 但这并不能将像 String 这样的构造函数解析为 string 类型——你仍然依赖于你提供的类型。 OP 正在尝试使用运行时信息进行静态类型化。
-
我认为你真正想要的是一个union type,它强制属性 inputType 和 type 之间的关系。
标签: javascript reactjs typescript types