Typescript扩展数组返回Max

时间:2015-09-12 13:39:03

标签: typescript1.5

您可以这样做:

class Person {
    constructor (public Name : string, public Age: number) {}
}

var list = new Array<Person>();
list.push(new Person ("Baby", 1));
list.push(new Person ("Toddler", 2));
list.push(new Person("Teen", 14));
list.push(new Person("Adult", 25));

var oldest_person = list.reduce( (a, b) => a.Age > b.Age ? a : b );
alert(oldest_person.Name);

但这样做会更好:

list.Max( (a) => a.Age);

有关如何在TypeScript通用中实现的建议?

1 个答案:

答案 0 :(得分:2)

Array进行子类化,因此我们不会修改Array.prototype

class List<Item> extends Array<Item> {
  Max<Selected>(select: (item: Item) => Selected): Item {
    return this.reduce( (a: Item, b: Item): Item => select(a) > select(b) ? a : b );
  }
}

class Person {
  constructor (public Name : string, public Age: number) {}
}

var list = new List<Person>();
list.push(new Person("Baby", 1));
list.push(new Person("Toddler", 2));
list.push(new Person("Teen", 14));
list.push(new Person("Adult", 25));

var oldest_person = list.Max( (a) => a.Age)
alert(oldest_person.Name);

Try it in TypeScript Playground