What is the best way to write utilities in TypeScript?

Oleg Varaksin
1 min readJul 18, 2018

--

There are two main ways to write utility functions in TypeScript:

A) Quite normal functions (grouped in a file)
B) Static methods of a class

Examples of both:

What is the best one? The answer is A). In the TypeScript documentation says:

“Consumers of your module should have as little friction as possible when using things that you export. Adding too many levels of nesting tends to be cumbersome, so think carefully about how you want to structure things. Exporting a namespace from your module is an example of adding too many layers of nesting. While namespaces sometime have their uses, they add an extra level of indirection when using modules. This can quickly become a pain point for users, and is usually unnecessary. Static methods on an exported class have a similar problem — the class itself adds a layer of nesting. Unless it increases expressivity or intent in a clearly useful way, consider simply exporting a helper function.”

And that’s clear. Bundlers, such as Webpack, already adds a namespace (enclose a file content in a function). TypeScript compiler does the same with a transpiled class. At the end we have nested namespaces.

Imports are not a problem. Most IDEs import functions automatically. If you want, you can also group imports as follows:

import * as <mynamespace> from <somepath>

Have fun!

--

--

Oleg Varaksin
Oleg Varaksin

Written by Oleg Varaksin

Thoughts on software development. Author of “PrimeFaces Cookbook” and “Angular UI Development with PrimeNG”. My old blog: http://ovaraksin.blogspot.de

Responses (2)