Issue
On an Angular 12 application I created the following extension:
declare global {
interface String {
toNumber(): number | null;
}
}
Object.defineProperty(String.prototype, "toNumber", {
value: function(this: string) {
return Number(this) || null;
}
});
When using in an Angular's component:
var number = stringValue.toNumber();
I get the error:
Property 'toNumber' does not exist on type 'string'.
What is the best way to use such extensions in Angular?
Do I need to change the way I am creating the extension?
Solution
You can achieve that like the following:
- Under
srcfolder createglobal.d.tsfile to define the signature of the extension method, with the following content:
declare global {
interface String {
toNumber(): number | null;
}
}
export {}; // to define this file as a module
- Add the implementation of the extension method within file
string.extension.tsanywhere undersrcfolder, with the following content:
Object.defineProperty(String.prototype, "toNumber", {
value: function(this: string) {
return Number(this) || null;
}
});
export {}; // to define this file as a module
- Import the
string.extension.tsfile inapp.module.ts:
import 'PATH_TO_YOUR_FILE/string-extension'
Answered By - Amer
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.