这篇文章上次修改于 818 天前,可能其部分内容已经发生变化,如有疑问可询问作者。

我打算在一个使用 TS 的项目里面编写一个 React 表格组件,定义 props 的时候需要用到一个泛型对象(一个数组里面包含多个泛型对象,不限制键名),毕竟总不可能一直 any 一劳永逸吧!

我对 TypeScript 依旧不够轻车熟路,查了波文档结果搞出来了 2 个写法,但这样的定义貌似都是一致的。

@Innei 告诉我,这种情况使用 Record(第 3 种写法)更合适,因为这是一个 TS 的内置对象,可以节省掉一个 Interface,更简单明了。

方法 A

Array<泛型定义>

interface IRowsItem {
  [propName: string]: string | number
}

interface TableProps {
  rows: Array<IRowsItem>
}

方法 B

泛型定义[]

interface IRowsItem {
  [propName: string]: string | number
}

interface TableProps {
  rows: IRowsItem[]
}

方法 C

Record 指定对象类型

interface TableProps {
  rows: Record<string, string | number>
}

适用对象

传入一个 props.rows 值,以下形式的对象都是符合其类型的:

[
  {
    name: "Paul",
    age: 18,
    desc: "I am Paul, the vegetable frontend."
  }
]

或者是

[
  {
    id: 1,
    date: "2021-06-02 18:00:00",
    type: 2,
    title: "Sth about Dreamer-Paul"
  }
]