Extension methods in typescript (system)

后端 未结 2 1147
无人及你
无人及你 2021-02-07 08:50

In my angular2 project I\'m trying to extend the prototype of the string class using typescript. This is my code:

interface String 
{
    startsWith(s:         


        
相关标签:
2条回答
  • 2021-02-07 09:10

    I was able to get it working with no TS errors (1.8.9), Angular2 (2.0.0-beta.12) errors, and working function call using the following template:

    tsconfig.json

    {
      "compilerOptions": {
      "target": "es5",
      "module": "system",
      "moduleResolution": "node",
      "sourceMap": true,
      "emitDecoratorMetadata": true,
      "experimentalDecorators": true,
      "removeComments": false,
      "noImplicitAny": false
    },
    "exclude": [
      "node_modules",
      "typings/main",
      "typings/main.d.ts"
      ]
    }
    

    Next, create (if one doesn't exist) a global.d.ts file local to your project:

    global.d.ts (local to project, not main TS file of same name)

    export {}
    
       declare global {
         interface String {
           calcWidth(): number;
         }
       }
    

    extensions.ts (entire file)

    export {}
    
    //don't redefine if it's already there
    if (!String.prototype.hasOwnProperty('calcWidth')) {
        String.prototype.calcWidth = function (): number {
          //width calculations go here, but for brevity just return length
          return this.length;
        }
    }
    

    Then in your whatever your first System.import(filename) is (mine is main.ts). Just use once:

    import './extensions'  //or whatever path is appropriate
    ... 
    ...
    

    Now, throughout your app you can use your interface:

    var testString = 'fun test';
    console.log(testString.calcWidth());
    

    Produces console output:

    8
    

    Hope this is helpful.

    0 讨论(0)
  • 2021-02-07 09:24

    Instead of importing the code in html just put this at the top of your code:

    import './utils/extensions';
    

    Just replace it with your path to the file.

    Here are some more resources on modules and imports:

    TypeScript docs

    MDN docs

    0 讨论(0)
提交回复
热议问题