0

I was learning Typescript and came across the term union types. As far as I understood, it allows us to have kinda "restriction" on what types or specific values we are working on. But the question is what is the benefit of this restriction, I admit, it will lead to secure code but what is the benefit of the secure code.

Sukich
  • 139
  • 1
  • 8
  • 1
    "*what is the benefit of the secure code*" it feels like this question answers itself. What do you think the purpose of TypeScript is aside from union types? – VLAZ Jan 02 '20 at 09:28
  • The whole type system in TypeScript was introduced for us to write more secure code. The benefit of the secure code is secure code. You have answered your question in the question. – Sebastian Kaczmarek Jan 02 '20 at 09:33
  • @SebastianKaczmarek, sorry the question seems a bit weird but I a bit cannot get the meaning behind secure code. Please can you give some examples of the importance of secure code. – Sukich Jan 02 '20 at 09:38
  • 3
    `function add(a, b) { return a + b }` vs `function add(a: number, b: number) : number { return a + b; }` when you call `add("banana", {hello: "world"})` – VLAZ Jan 02 '20 at 09:40
  • 1
    @VLAZ gave very simple and good example. Without type declaration, nothing stops you from calling `add` with non-number arguments which can lead to unexpected behavior of your app and potentially hard to debug problems. With strictly declared types as numbers, you can no longer call `add` with non-number arguments because an error will be thrown on the parsing level. Declaring types make your code more secure. – Sebastian Kaczmarek Jan 02 '20 at 09:48

1 Answers1

2

In dynamically typed languages like javascript it can sometimes be quite difficult to find the reason for run-time errors. Using a type-system you periodically (for example when calling a function) check the type of your parameters and ensure their structure is what you expect them to be. This way you often get easier to understand errors for your bugs, which saves some time when debugging and additionally you might also detect bugs you wouldn't have noticed otherwise.

For example think of function doing some numeric computation and you accidentally passed nothing to this function. Instead of wondering about strange errors in your function you immediately know the error occurred earlier.

Because the javascript web API often makes use of dynamic types, e.g. find might return undefined or the found element, TypeScript has to use UnionTypes to allow this.

Corylus
  • 736
  • 5
  • 16
  • 2
    "*TypeScript has to use UnionTypes to 'weaken' the type-system a little bit to allow this.*" I disagree - I'd say union types lead to *stronger* type systems. Even Haskell has union types and it's a strongly typed language. – VLAZ Jan 02 '20 at 10:00
  • I will remove the word 'weaken' (That's why I used quotation marks). – Corylus Jan 02 '20 at 10:04