Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I import functions into a typescript class file?

I have Typescript classes that look like this:

class WordService implements IWordService {

    wordCreatedById: number = 0;
    wordModifiedById: number = 0;

    static $inject = [
        "$http",
        "$q",
        ...
    ];

    constructor(
        public $http: ng.IHttpService,
        public $q: ng.IQService,
        ...
    ) {

    }

    wordClear = (): void => {
        this.word = null;
        this.wordBase = null;
    }

    ...

}

My class files have become very long now as I defined more and more functions like wordClear.

Is there any way that I could move functions into another file and import them into my class?

like image 724
Samantha J T Star Avatar asked Dec 19 '22 17:12

Samantha J T Star


1 Answers

If you're asking about using other functions in class definitions this is one way to accomplish it. Let's put this in utilFunctions.ts (or whatever you want to call it.

export function wordClear(obj:{word:any, wordBase:any}/*replace with relevant interface*/) :void {
    obj.word = null;
    obj.wordBase = null;
}

and then in the class ts file

import * as utilFunctions from './utilFunctions'

class WordService implements IWordService {
    ...
    wordClear = ()=>utilFunctions.wordClear(this);
}

Or

import * as utilFunctions from './utilFunctions'

class WordService implements IWordService {
    ...
    public wordClear() {
        utilFunctions.wordClear(this);
    }
}
like image 51
Paarth Avatar answered Dec 23 '22 13:12

Paarth