简体   繁体   English

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

[英]Can I import functions into a typescript class file?

I have Typescript classes that look like this: 我有这样的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;
    }

    ...

}

My class files have become very long now as I defined more and more functions like wordClear. 我的类文件已经变得很长了,因为我定义了越来越多的函数,比如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. 我们把它放在utilFunctions.ts(或者你想要的任何东西)中。

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 然后在类ts文件中

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何从其他javascript文件导入函数? - How can I import functions from an other javascript file? 打字稿导入-每个文件约定一个类 - Typescript import - One class per file convention 从TypeScript中的另一个文件导入类 - Import class from another file in TypeScript 打字稿:如何从javascript文件导入一个类? - Typescript: how to import a class from a javascript file? 从其他文件导入函数到类 - Import functions to class from a different file 如何在JavaScript文件中引用导出的Typescript类? - How can I reference an exported typescript class in my JavaScript file? 尝试从外部文件导入类时,如何解决Typescript中的Uncaught ReferenceError? - How do I fix Uncaught ReferenceError in Typescript when trying to import class from external file? 如何在运行时访问Typescript类的公共属性(调试)? 仅构造函数和函数可访问 - how can I access typescript class public property at run time (debugging)? only the constructor and functions are accessible 为什么我不能在TypeScript类中声明局部变量和函数? - Why can't I declare local variables and functions within a TypeScript class? Typescript:如何完成 class(在运行时注册)的动力学方法/功能? - Typescript: how can I have completion for dynamics method/functions of a class (registered at runtime)?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM