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 bee 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?
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 bee 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?
Share Improve this question asked May 15, 2016 at 7:18 Samantha J T StarSamantha J T Star 32.8k89 gold badges256 silver badges441 bronze badges 2- Are you asking about importing functions from other files or about partially defining classes? – Paarth Commented May 15, 2016 at 7:30
- You can import function from other files, and then you can call such functions from your class methods, but that's not the right way to deal with the problem. Large classes are considered "a bad smell", and you should break such classes into smaller ones. – Nitzan Tomer Commented May 15, 2016 at 7:34
1 Answer
Reset to default 13If you're asking about using other functions in class definitions this is one way to acplish 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);
}
}