I created a basic extension on the Date object, and it works fine. Below is my CODE:
date.extensions.ts
export {}
declare global {
interface Date {
toSQLiteString(): string;
}
}
Date.prototype.toSQLiteString = function() {
let tzo = -this.getTimezoneOffset();
let dif = tzo >= 0 ? '+' : '-';
let pad = function(num) {
let norm = Math.abs(Math.floor(num));
return (norm < 10 ? '0' : '') + norm;
};
return this.getFullYear() +
'-' + pad(this.getMonth() + 1) +
'-' + pad(this.getDate()) +
'T' + pad(this.getHours()) +
':' + pad(this.getMinutes()) +
':' + pad(this.getSeconds()) +
dif + pad(tzo / 60) +
':' + pad(tzo % 60);
};
Now, I want to create an extension file on a custom object, lets call it MyModel. This object is defined in another file and looks like so (very simple example)
export class MyObject {
id: number = 0;
name: string = ''
}
Now i want to create a file called MyObject.extensions.ts and have an extension function, so i have created this and the file looks like so
import { MyObject } from './my-object.ts'
export {}
declare global {
interface MyObject {
getIdAndName(): string;
}
}
MyObject.prototype.getIdAndName = function() {
return this.id + ' - ' + this.name;
};
But, for some reason I am am getting an error by typescript

If however, i remove the import at the top of the file, the error disappears, but i get a different error, as below

I am using typescript 2.4.2
Any suggestions much appreciated
Your class is not in the global namespace it is in a module, you should extend the module declaration :
import { MyObject } from './my-object'
export {}
declare module './my-object' {
interface MyObject {
getIdAndName(): string;
}
}
MyObject.prototype.getIdAndName = function() {
return this.id + ' - ' + this.name;
};
Also remove the .ts extension from your module import.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With