ReScript JSX中option<T>=?与直接=?的区别是什么?
ReScript React可选children参数的类型差异解析
先看你给出的组件代码:
module OptionalChildren = { @react.component let make = (~children: option<React.element>=?, ~children2: React.element=?) => { <div> {switch children { | Some(element) => element | None => React.string("No children provided") }} {switch children2 { | Some(element) => element | None => React.string("No children provided") }} </div> } }
问题解答
- 是的,
children和children2最终都会被推断为option<React.element>类型,但二者的写法逻辑有区别,后者并非前者的简写:
显式声明option类型的
children
这里你直接将children的类型标注为option<React.element>,同时加上=?标记可选参数。在ReScript React的@react.component注解规则下,即便不写=?,只要类型是option<...>,参数也会被处理成可选的;加上=?只是让写法更直观,明确告知开发者这是一个可选参数。普通类型加
=?的children2
这里你标注的类型是React.element,但添加了=?,此时@react.component注解会自动将该参数的类型包装为option<React.element>,同时默认值设为None。这是ReScript React专门提供的语法糖:给非option类型的参数加上=?,编译器会自动完成可选类型的转换。
总结
- 两种写法最终得到的参数类型完全一致
- 前者是显式声明可选类型,写法更直白;后者是利用注解语法糖自动包装,写法更简洁
- 二者只是实现相同效果的不同写法,不存在简写关系
内容的提问来源于stack exchange,提问作者Harshal Patil
相关产品推荐
相关产品推荐

