简体   繁体   中英

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?

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);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM