mercredi 13 septembre 2017

Property does not exist on type 'MyObject' - Typescript extension

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

enter image description here

I am using typescript 2.4.2

Any suggestions to improve my code?




Aucun commentaire:

Enregistrer un commentaire