0

In my Ionic2 project, I am trying to add a new method to Number as in the following code.

interface StringConstructor {
  bar(msg: string): void;
}

String.bar = function(msg: string) {
  alert("Example of static extension: " + msg);
}

String.bar("Hello World");


interface NumberConstructor {
  toRad(): number;
}

Number.toRad = function() { return this * (Math.PI / 180); }; 

export function gpsDist() {
  
}

When I do ionic build, it gives me the following errors:

TypeScript error: /Users/cju/Projects/Bus2-App/app/util/mathUtil.ts(7,8): Error TS2339: Property 'bar' does not exist on type 'StringConstructor'.

TypeScript error: /Users/cju/Projects/Bus2-App/app/util/mathUtil.ts(11,8): Error TS2339: Property 'bar' does not exist on type 'StringConstructor'.

TypeScript error: /Users/cju/Projects/Bus2-App/app/util/mathUtil.ts(18,8): Error TS2339: Property 'toRad' does not exist on type 'NumberConstructor'.

However the same file compiles ok outside ionic. If I compile it with tsc, I get no errors. All the code are in one file.

1
  • I tried to compile the file outside "ionic build" command by doing "node tsc.js myfile.ts" and "node typescript.js myfile.ts", both compile without error. The tsc.js and typescript.js come from ionic-gulp-browserify-typescript/node_modules/tsify/node_modules/typescript/lib. Commented May 18, 2016 at 9:10

1 Answer 1

0

Angular takes care of ts compilation, you can edit the typescript compiler options in the file tsconfig.json which is in the root of your app. But I don't think you want to mess with that.

Try the non-static way to extend functionality that you can find here: https://stackoverflow.com/a/13897813/1016128

Sign up to request clarification or add additional context in comments.

1 Comment

I did this. interface Number { toRad(): number; } Number.prototype.toRad = function() { return this * 2; }; It still gives me the error "Error TS2339: Property 'toRad' does not exist on type 'Number'." But it still runs and gives me the correct result.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.