Reader small image

You're reading from  TypeScript 4 Design Patterns and Best Practices

Product typeBook
Published inSep 2021
Reading LevelIntermediate
PublisherPackt
ISBN-139781800563421
Edition1st Edition
Right arrow
Author (1)
 Theofanis Despoudis
Theofanis Despoudis
author image
Theofanis Despoudis

Theo Despoudis lives in Ireland, where he works as a Software Engineer for WP Engine and as a part-time tech practitioner for Fixate. He is the co-author of The React Workshop and Advanced Go Programming in 7 Days, Dzone Core Member, and maintains some open source projects on GitHub. Theo is available for conference talks, independent consulting, and corporate training services opportunities.
Read more about Theofanis Despoudis

Right arrow

Not using runtime assertions

TypeScript safety comes from compile-time checks when writing code. You define a type for a value and then TypeScript verifies its fair usage. This process, however, covers only 50% of the safety in general. The other 50% comes from runtime safety. For example, let's take the following function in TypeScript:

RuntimeAssertions.ts

function divMod(x: number, y: number): [number, number] {
  return [Math.floor(x / y), x % y];
}

This gets compiled in JavaScript as follows:

"use strict";
function divMod(x, y) {
    return [Math.floor(x / y), x % y];
}

Looking at the aforementioned code, you could guess that there are many potential dangers here:

  • The x and y parameters might not be numbers. If they are numbers encoded as strings, it will work but not if they are not a real number value:
    > divMod("1", 2)
    (2) [0, 1]
    > divMod("a", 2)
  • Here in the second case, we passed...
lock icon
The rest of the page is locked
Previous PageNext Page
You have been reading a chapter from
TypeScript 4 Design Patterns and Best Practices
Published in: Sep 2021Publisher: PacktISBN-13: 9781800563421

Author (1)

author image
Theofanis Despoudis

Theo Despoudis lives in Ireland, where he works as a Software Engineer for WP Engine and as a part-time tech practitioner for Fixate. He is the co-author of The React Workshop and Advanced Go Programming in 7 Days, Dzone Core Member, and maintains some open source projects on GitHub. Theo is available for conference talks, independent consulting, and corporate training services opportunities.
Read more about Theofanis Despoudis