userMod2
userMod2

Reputation: 8960

Typescript - Using an abstract class to simple share a function

Using Typescript, I have 2 functions, within them they have the exact same function code. Therefore I decided to take that common function out into its own file.

However I've done it like below - and wonder should I instead be creating an abstract class which has that function (others will go in there soon). Or is it just as nice to keep it as I've done at the moment.

So file 1:

import { sharedFunction } from "../common/actions";

export async function onTrigger(context: Context, documents: Resource[] | null): Promise<void> {
   sharedFunction(aParamFile1, bParamFile1)
}

file 2:

import { sharedFunction } from "../common/actions";

export async function onTrigger(context: Context, documents: Resource[] | null): Promise<void> {
   sharedFunction(aParamFile2, bParamFile2)
}

actions file with shared function:

export async function sharedFunction(input1: someType, input2: someType){
   //Do something
}}

The reason I wonder if it should be an abstract class is say I have several functions I want to use in file1 or file2 I'd need to list them all in the import lines at the top. Is that seen as untidy design or is it acceptable? I was wondering whether it could be avoided so instead do myAbstractClass.sharedFunction?

But on the other hand I don't see how that onTrigger function can extend that abstract class being a function.

Any ideas/advice appreciated.

Thanks.

Upvotes: 0

Views: 63

Answers (1)

Instead of introducing an artificial namespace class (which you don't really need), you can just change your import to:

import * as shared from '../common/actions';

This will import everything from that module. Then prefix the functions thus imported with shared..

Upvotes: 1

Related Questions