给组件 Props 添加类型后,编辑器可以提示必填字段,也能在传错数据时尽早发现问题。

声明组件需要的数据

TSX
type NoticeProps = {
  title: string
  description: string
  tone?: 'info' | 'success' | 'warning'
}

function Notice({ title, description, tone = 'info' }: NoticeProps) {
  return <section data-tone={tone}><h2>{title}</h2><p>{description}</p></section>
}

title 和 description 是必填项;tone 后面的问号表示可选,并在解构时提供默认值。

选择 type 还是 interface

描述对象形状时,两者都能完成常见任务。团队已有约定时跟随约定即可,重点是让组件接口容易读、容易更新。

小结

先把真正需要的 Props 写出来,避免一开始为所有可能性增加复杂类型。随着组件复用范围扩大,再补充变体或泛型也不迟。