Extend native JavaScript array

后端 未结 10 885
情书的邮戳
情书的邮戳 2020-11-27 22:08

Is there any way to inherit a class from JS native function?

For example, I have a JS function like this:

function Xarray()
{
    Array.apply(this, a         


        
10条回答
  •  青春惊慌失措
    2020-11-27 22:48

    Yes you can augment the Builtin types and do it in a way that doesn't require all the paraphernalia of an XArray as described in the other answers and is closer to how you would do it in javascript.

    Typescript allows a number of ways to do this, but for the Builtin types like Array and Number you need to use "merging" and declare the global namespace to augment the types, see the docs

    so for Array we can add an optional metadata object and a get first member

    declare global {
      interface Array {
        meta?: any|null ,
        getFirst(): T
      }
    }
    
    if(!Array.prototype.meta )
    {
      Array.prototype.meta = null
    }
    if(!Array.prototype.getFirst )
    {
      Array.prototype.getFirst = function() {
        return this[0];
      }
    }
    

    we can use this like so:

    let myarray: number[] = [ 1,2,3 ]
    myarray.meta = { desc: "first three ints" }
    let first: number = myarray.getFirst()
    

    The same goes for Number say I want to add a modulo function that isn't limited like the remainder %

    declare global {
      interface Number {
        mod(n:number): number
      }
    }
    
    if(!Number.prototype.mod )
    {
      Number.prototype.mod = function (n: number) {
              return ((this % n) + n) % n;
      }
    }
    

    and we can use it like so:

    let foo = 9;
    console.log("-9.mod(5) is "+ foo.mod(5))    
    

    For Functions that we may want to add an API to ie to make it behave like a function and an object we can use hybrid types (see docs)

    // augment a (number) => string  function with an API
    interface Counter {
        (start: number): string;
        interval: number;
        reset(): void;
    }
    
    //helper function to get my augmented counter function with preset values
    function getCounter(): Counter {
        let counter = function (start: number) { };
        counter.interval = 123;
        counter.reset = function () { };
        return counter;
    }
    

    use it like so:-

    let c = getCounter();
    c(10);
    c.reset();
    c.interval = 5.0;
    

提交回复
热议问题