Skip to content Skip to sidebar Skip to footer

Extending Built-in Types In Typescript

I have the following structure: project |- types |- global.d.ts |- string.d.ts |- wdio.d.ts |- src |- Models |- Resources |- Components |- Extensions

Solution 1:

Full working example on Github

Place your String interface extension in a random .d.ts file:

interface String {
  myCustomFn(text : string) : string;
}

Add another file extension.ts where you add the prototype:

String.prototype.myCustomFn = function(text : string) : string {
  return'myCustomFn';
};

Then import the extension.ts file into your root index.ts file:

import'./extension';

Now you can add your String().myCustomFn(text: string); everywhere you want.

P.S. it is important that you include the .d.ts file to your compilation files. The typeRoots property is not necessary.

tsconfig.json:

{
  "compilerOptions": {
    "outDir": "dist"
  },
  "include": [
    "src",
    "types"// here is the .d.ts file
  ],
  "exclude": [
    "**/node_modules"
  ]
}

Post a Comment for "Extending Built-in Types In Typescript"