Extending Array in TypeScript

匿名 (未验证) 提交于 2019-12-03 02:20:02

问题:

How to add a method to a base type, say Array? In the global module this will be recognized

interface Array {    remove(o): Array; }

but where to put the actual implementation?

回答1:

You can use the prototype to extend Array:

interface Array {    remove(o: T): Array; }  Array.prototype.remove = function (o) {     // code to remove "o"     return this; }


回答2:

declare global seems to be the ticket as of TypeScript 2.1. Note that Array.prototype is of type any[], so if you want to have your function implementation checked for consistency, best to add a generic type parameter yourself.

declare global {   interface Array {     remove(elem: T): Array;   } }  if (!Array.prototype.remove) {   Array.prototype.remove = function(elem: T): T[] {     return this.filter(e => e !== elem);   } }


回答3:

From TypeScript 1.6, you can "natively" extend arbitrary expressions like inbuilt types.

What's new in TypeScript:

TypeScript 1.6 adds support for classes extending arbitrary expression that computes a constructor function. This means that built-in types can now be extended in class declarations.

The extends clause of a class previously required a type reference to be specified. It now accepts an expression optionally followed by a type argument list. The type of the expression must be a constructor function type with at least one construct signature that has the same number of type parameters as the number of type arguments specified in the extends clause. The return type of the matching construct signature(s) is the base type from which the class instance type inherits. Effectively, this allows both real classes and "class-like" expressions to be specified in the extends clause.

// Extend built-in types  class MyArray extends Array { } class MyError extends Error { }  // Extend computed base class  class ThingA {     getGreeting() { return "Hello from A"; } }  class ThingB {     getGreeting() { return "Hello from B"; } }  interface Greeter {     getGreeting(): string; }  interface GreeterConstructor {     new (): Greeter; }  function getGreeterBase(): GreeterConstructor {     return Math.random() >= 0.5 ? ThingA : ThingB; }  class Test extends getGreeterBase() {     sayHello() {         console.log(this.getGreeting());     } }


回答4:

class MyArray extends Array {     remove: (elem: T) => Array = function(elem: T) {         return this.filter(e => e !== elem);     } } let myArr = new MyArray(); myArr.remove("some");

this works for me with typescript v2.2.1!



转载请标明出处:Extending Array in TypeScript
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!