1. 列表组件接口设计
// 定义列表项类型,使用泛型T
interface ListItem<T> {
value: T;
// 其他可能的属性,例如用于展示的文本
label: string;
}
// 定义列表组件接口
interface ListComponent<T> {
items: ListItem<T>[];
// 渲染列表项的方法,这里假设接受一个函数,返回渲染后的HTML字符串
renderItem: (item: ListItem<T>) => string;
}
2. 列表组件实现
class List<T> implements ListComponent<T> {
constructor(public items: ListItem<T>[], public renderItem: (item: ListItem<T>) => string) {}
render() {
let html = '<ul>';
this.items.forEach(item => {
html += `<li>${this.renderItem(item)}</li>`;
});
html += '</ul>';
return html;
}
}
3. 泛型在该场景下的作用
- 提高代码复用性:通过使用泛型
T
,列表组件可以适用于不同类型的数据。例如,既可以是 string
类型的数据列表,也可以是自定义对象类型的数据列表,而无需为每种数据类型单独编写一套列表组件代码。如下示例:
// 使用string类型
const stringList = new List<string>(
[
{ value: 'item1', label: 'Item 1' },
{ value: 'item2', label: 'Item 2' }
],
item => item.value
);
console.log(stringList.render());
// 使用自定义对象类型
interface User {
id: number;
name: string;
}
const userList = new List<User>(
[
{ value: { id: 1, name: 'John' }, label: 'User 1' },
{ value: { id: 2, name: 'Jane' }, label: 'User 2' }
],
item => item.value.name
);
console.log(userList.render());
- 增强类型安全性:TypeScript 的类型检查机制会根据传入的泛型类型
T
对列表组件的操作进行类型检查。比如在 renderItem
函数中,传入的 item
类型会根据 T
准确确定,避免了在运行时因为类型不匹配而产生的错误,使得代码更加健壮。