classStudentList<T>{ constructor(private list : T []){} getSingleStudent(index:number): T { returnthis.list[index]; } } const studentList = new StudentList<string>(['vanlus','jokerwan','hehe']); console.log(studentList.getSingleStudent(2));
泛型约束,extends
1 2 3 4 5 6 7 8
classStudentList<Textends (number | string)>{ constructor(private list : T []){} getSingleStudent(index:number): T { returnthis.list[index]; } } const studentList = new StudentList<string>(['vanlus','jokerwan','hehe']); console.log(studentList.getSingleStudent(2));
泛型中的继承接口: 需要我们传入的数组结构是对象,且有name字段,并且返回name值
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
interface Student{ name : string } classStudentList<TextendsStudent>{ constructor(private list : T []){} getSingleStudent(index:number): string{ returnthis.list[index].name; } } const studentList = new StudentList([ {name:'vanlus'}, {name:'jokerwan'}, {name:'hehe'} ]); console.log(studentList.getSingleStudent(2));