user3781239
user3781239

Reputation: 151

Exporting a collection of functions in Typescript

I'm new to Typescript and I've spent a while searching up various methods to do this, but I'm stuck.

I want to create a library file that just contains a collection of unrelated functions that I can import anywhere. In regular Javascript, I can just do something similar to this:

let libraryFunctions = {};
libraryFunctions.a = () => {
  return true;
}
module.exports = libraryFunctions;

However, in Typescript I just get a complaint saying Property 'a' does not exist on type {}. I then saw I could so something similar to this:

interface ILibraryFunctions {
  a(): boolean;
};

export class LibraryFunctions implements ILibraryFunctions {
  a = () => {
    return false;
  }
}

However, creating a class seems to be too excessive (unless if my understanding of Typescript's class is wrong). Would anyone be able to point me in the right direction?

Thanks!

Upvotes: 2

Views: 1887

Answers (1)

Madara's Ghost
Madara's Ghost

Reputation: 175088

In TypeScript, you just export whatever you want, similarly to ES2015 modules (which are also implemented by babel):

export function a() {
  return true;
}

// or alternatively

export const b = () => false

Then, in another file

import {a, b} from './thatFirstFile';
// or
import * as libraryFunctions from './thatFirstFile';

As for your specific scenario, you don't need to implement a class:

interface ILibraryFunctions {
  a(): boolean;
};

const myLib: ILibraryFunctions = {
  a() { return true; }
};

export default myLib;

That said, the method mentioned at the top of the answer is preferable, from Daniel's comment below:

Realistically, you wouldn't export default an object with a, you'd directly default-export a itself. That said, a reason you wouldn't do what was written is that existing tools can more-easily tree-shake from the top-level exports, but not from an actual object. Additionally, using the first syntax allows you to use ES2015's named import syntax when you have more than one export.

Upvotes: 3

Related Questions