Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
165 views
in Technique[技术] by (71.8m points)

javascript - How do I split a TypeScript class into multiple files?

I found a lot of examples and also tried myself to split a module into several files. So I get that one, very handy. But it's also practical sometimes to split a class for the same reason. Say I have a couple of methods and I don't want to cram everything into one long file.

I'm looking for something similar to the partial declaration in C#.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Lately I use this pattern:

// file class.ts
import { getValue, setValue } from "./methods";

class BigClass {
    public getValue = getValue;
    public setValue = setValue;

    protected value = "a-value";
}
// file methods.ts
import { BigClass } from "./class";

function getValue(this: BigClass) {
    return this.value;
}

function setValue(this: BigClass, value: string ) {
   this.value = value;
}

This way we can put methods in a seperate file. Now there is some circular dependency thing going on here. The file class.ts imports from methods.ts and methods.ts imports from class.ts. This may seem scary, but this is not a problem. As long as the code execution is not circular everything is fine and in this case the methods.ts file is not executing any code from the class.ts file. NP!

You could also use it with a generic class like this:

class BigClass<T> {
    public getValue = getValue;
    public setValue = setValue;

    protected value?: T;
}

function getValue<T>(this: BigClass<T>) {
    return this.value;
}

function setValue<T>(this: BigClass<T>, value: T) {
    this.value = value;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...