我可以将函数导入到typescript类文件中吗

Can I import functions into a typescript class file?

本文关键字:文件 typescript 函数 导入 我可以      更新时间:2023-09-26

我有如下的Typescript类:

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

随着我定义了越来越多的函数,我的类文件现在变得很长了比如wordClear。

有什么方法可以将函数移到另一个文件中并导入它们吗进入我的课堂?

如果你想在类定义中使用其他函数,这是实现它的一种方法

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

然后在类ts文件中

import * as utilFunctions from './utilFunctions'
class WordService implements IWordService {
    ...
    wordClear = ()=>utilFunctions.wordClear(this);
}

import * as utilFunctions from './utilFunctions'
class WordService implements IWordService {
    ...
    public wordClear() {
        utilFunctions.wordClear(this);
    }
}