Post

Typescript Pt. 2 - JavaScript Issues

Some of the JavaScript issues that Typscript solves

1. Type checking

  • JavaScript is a dynamically typed language, which means that you don’t have to specify the type of variables when you declare them. The type will be determined automatically while the program is being processed by the JavaScript engine.
1
2
let a = 10;
a = "hello"; // This is allowed in JavaScript
  • TypeScript is a statically typed language, which means that you have to specify the type of variables when you declare them. The type will be checked by the TypeScript compiler before the program is executed.
1
2
let a: number = 10;
a = "hello"; // This is not allowed in TypeScript

2. Type inference

In TypeScript, you don’t have to specify the type of variables all the time. The TypeScript compiler can infer the type of a variable based on its value.

1
2
let a = 10; // The type of a is number
let b = "hello"; // The type of b is string

3. Type annotations

In TypeScript, you can specify the type of a variable explicitly.

1
2
let a: number = 10;
let b: string = "hello";

4. Type aliases

In TypeScript, you can create a new name for a type using the type alias feature.

1
2
3
4
5
type Age = number;
type Person = {
  name: string;
  age: Age;
};

Some wierd JavaScript behavior

1
2
3
4
5
6
7
8
9
10
typeof null; // object
null * 1; // 0
undefined * 1; // NaN

const shape = {
  width: 100,
  height: 100,
};

shape.heigth; // undefined
This post is licensed under CC BY 4.0 by the author.