Brad Woods Digital Garden

Notes / JavaScript / TypeScript

The Warhammer 40k Adeptus Mechanicus symbol

Table of contents

    A square with the letters 'TS'

    TypeScript

    Planted: 

    Tended: 

    Status: decay

    Hits: 184

    Intended Audience: Front-end developers

    Advantages

    TypeScript provides the following advantages over vanilla JavaScript:

    • self-documentation,
    • tooling that can be built on top of it, improving developer experience (example: IntelliSense) and
    • through static analysis, it eliminates an entire class of runtime bugs (example: where a function gets passed an object it doesn't know how to handle and fails at runtime).

    Don't Use Enums

    Execute Program did a great break down of the benefits of using unions instead of enums. Their main argument is TypeScript is supposed to be JavaScript, but with static type features added. If we remove all of the types from TypeScript code, what's left should be valid JavaScript code. For example:

    TypeScript Code

    /index.ts

    function add(x: number, y: number): number {
    return x + y;
    }

    TypeScript Removed

    /index.js

    function add(x, y) {
    return x + y;
    }

    Enums break this rule. If enums were removed like other type features, you would have JavaScript code referencing nothing:

    TypeScript Code

    /index.ts

    enum HttpMethod {
    Get = 'GET',
    Post = 'POST',
    }
    const method: HttpMethod = HttpMethod.Post;
    method; // Evaluates to 'POST'

    TypeScript Removed

    /index.js

    const method = ???;
    method;

    I agree with Execute Program. I don't believe the benefits of enums outweigh the complication they add to the TypeScript complier model and the possibility of difficult bugs hidden in build steps.

    Feedback

    Have any feedback about this note or just want to comment on the state of the economy?

    Where to next?

    JavaScript
    Arrow pointing downYOU ARE HERE
    A Johnny Cab pilot