DEV Community

Cover image for JavaScript vs TypeScript. Why We Should Learn TypeScript?
hiro9108
hiro9108

Posted on

JavaScript vs TypeScript. Why We Should Learn TypeScript?

What is TypeScript?

Hello, I am a student in Vancouver, Canada and studying web development. In this article, I will show you "How to use basic typescript data type" and "Why we should learn typescript".

JavaScript is one of the most popular programming languages.
Because that is not strict syntax than other languages. In the other words, JavaScript is more free style language but if you meet a lot of codes in your project, that free style might be changed to pains.

Please look at this code.

// Can you guess the return value?
const pikachu = (a, b) => {
  return a + b;
}
Enter fullscreen mode Exit fullscreen mode

Can you guess the return value of this code?
I cannot do it. Because pikachu function can take all types of variables like string, number and so on.

// Arguments is number.
const pikachu = (a, b) => {
  return a + b;
}
const result = pikachu(2021, 9);
console.log(result); // 2030
Enter fullscreen mode Exit fullscreen mode
// Arguments is string.
const pikachu = (a, b) => {
  return a + b;
}
const result = pikachu("2021", "9");
console.log(result); // 20219
Enter fullscreen mode Exit fullscreen mode

JavaScript is the language of dynamic typing. This is useful for writing codes more easily. But, developers have to take more care of what arguments are needed in the function, what value is returned from the function. More and More you read many codes, you realize this is stressful.

On the other hands, Please look at this code.

// Can you guess the return value?
const pikachu = (a: number, b: number): number => {
  return a + b;
}
Enter fullscreen mode Exit fullscreen mode

This is typescript code. TypeScript has static typing. When we look at this, we can probably guess pikachu function return value of number.
This is so useful to understand codes because companies have a lot of codes and that is so complicated.
So, we should use more readable methods because we take much time to read and understand codes which someone wrote in the past.

Basic Typescript

TypeScript has some primitive data types like string, number, boolean, null, undefined and so on.

This is the code of simple data types.

// string, number and boolean.
const caterpie01: number = 2021;    // OK
const caterpie02: number = false;   // NG

const Metapod01: string = "sleepy"; // OK
const Metapod02: string = true;     // NG

const Wartortle01: boolean = true;  // OK
const Wartortle02: boolean = 1111;  // NG
Enter fullscreen mode Exit fullscreen mode

We get compiled errors like this.

typescript.ts:10:7 - error TS2322: Type 'boolean' is not assignable to type 'number'.

10 const caterpie02: number = false;   // NG
         ~~~~~~~~~~

typescript.ts:13:7 - error TS2322: Type 'boolean' is not assignable to type 'string'.

13 const Metapod02: string = true;     // NG
         ~~~~~~~~~

typescript.ts:16:7 - error TS2322: Type 'number' is not assignable to type 'boolean'.

16 const Wartortle02: boolean = 1111;  // NG
         ~~~~~~~~~~~
Enter fullscreen mode Exit fullscreen mode

Next, please think about data type of null and undefined.

// null and undefined.
const Butterfree: null = null;
const ButterfreeNull: string = Butterfree;
console.log(ButterfreeNull) // null

const Kakuna: undefined = undefined;
const KakunaNull: string = Kakuna;
console.log(KakunaNull) //undefined
Enter fullscreen mode Exit fullscreen mode

This codes works in my environment. We can assign null and undefined value to string value.
In this case, I did not set the strict mode. Once I did assign strict mode to true, this code works like this.

typescript.ts:21:7 - error TS2322: Type 'null' is not assignable to type 'string'.

21 const ButterfreeNull: string = Butterfree;
         ~~~~~~~~~~~~~~

typescript.ts:25:7 - error TS2322: Type 'undefined' is not assignable to type 'string'.

25 const KakunaNull: string = Kakuna;
Enter fullscreen mode Exit fullscreen mode

That is good! We can catch type error.

You can set strict mode in tsconfig.json or use tsc command argument like
--strict. If you are not sure how to set up typescript environment, please check this web site.

What is any data type?

TypeScript has any data type. It allows all data types to work without type error. This is like vanilla javascript.
Please look at this sample code.

// any data type
let pidgey: any = 1991;
console.log(typeof pidgey) // number

pidgey = "bird";
console.log(typeof pidgey) // string

pidgey = false;
console.log(typeof pidgey) // boolean

pidgey = null;
console.log(typeof pidgey) // object

pidgey = undefined;
console.log(typeof pidgey) // undefined
Enter fullscreen mode Exit fullscreen mode

pidgey variable can be received all data type!

This is magical data types.🙀
If we use any data type, we do not use TypeScript at all. We just write code by using JavaScript.

TypeScript can guess data types if you do not defined that.
we can replace above sample codes with below codes.

// typescript can guess data types.
const caterpie01: number = 2021;     // number
const caterpie001 = 2021;            // number   - typescript guess


const Metapod01: string = "sleepy";  // string
const Metapod001 = "sleepy";         // string   - typescript guess

const Wartortle01: boolean = true;   // boolean
const Wartortle001 = true;           // boolean  - typescript guess
Enter fullscreen mode Exit fullscreen mode

This is more readable and shorter. Of course, we cannot assign another data type to this variable.

let caterpie001 = 2021;            // number
caterpie001 = "text";              // type error
Enter fullscreen mode Exit fullscreen mode

On the other hands, if we do not defined the data type of arguments in function, typescript judge the data type as any. Please check this code.

const pikachu = (a, b): number => {
  return a + b;
}
pikachu(2021, 9);
Enter fullscreen mode Exit fullscreen mode

I got the error like this.(My environment is that strict mode is true. If you turn off strict mode, you can success compile and do not see type error)

typescript.ts:57:18 - error TS7006: Parameter 'a' implicitly has an 'any' type.

57 const pikachu = (a, b): number => {
                    ~

typescript.ts:57:21 - error TS7006: Parameter 'b' implicitly has an 'any' type.

57 const pikachu = (a, b): number => {
Enter fullscreen mode Exit fullscreen mode

Because typescript cannot guess what values are received.
So, any data type were defined by typescript. When we use function in typescript, we have to defined data types of arguments like this.

const pikachu = (a: number, b: number): number => {
  return a + b;
}
Enter fullscreen mode Exit fullscreen mode

or

// Do not define the return value's data type.
const pikachu = (a: number, b: number) => {
  return a + b;
}
Enter fullscreen mode Exit fullscreen mode

If you create function with typescript, you absolutely have to define the specific data type. I recommend we do not have to use any data type anytime except specific situation. For one example, migrating codes from JavaScript to TypeScript.

Object data type

TypeScript can define the object data type with interface.
At first, look at this code.

// define object data type with interface.
interface PokemonObj {
  name: string,
  age: number,
  skill: string
}
// assign data type to object.
const pokemon: PokemonObj = {
  name: "pikachu",
  age: 6,
  skill: "Electric Shock!"
}
Enter fullscreen mode Exit fullscreen mode

We can use interface syntax for creating object data type. And then, assign it to object.
If we change data type of object, we get type error like this.

// define object data type with interface.
interface PokemonObj{
  name: string,
  age: number,
  skill: string
}
// assign data type to object.
const pokemon: PokemonObj = {
  name: "pikachu",
  age: "change age",       // change 
  skill: "Electric Shock!"
}
Enter fullscreen mode Exit fullscreen mode

This is type error message.

typescript.ts:75:3 - error TS2322: Type 'string' is not assignable to type 'number'.

75   age: "change age",
     ~~~

  typescript.ts:69:3
    69   age: number,
         ~~~
    The expected type comes from property 'age' which is declared here on type 'PokemonObj'
Enter fullscreen mode Exit fullscreen mode

We get type error. It is useful to define the data type of object with interface. Of course, we can define data type directly like this code.

// assign data type directly to object.
const pokemon: {name: string, age: number, skill: string} = {
  name: "pikachu",
  age: 6,
  skill: "Electric Shock!"
}
Enter fullscreen mode Exit fullscreen mode

Array data type

Array with data type is like this.

// define array data type
const pokemon: string[] = ["pikachu", "Raichu", "Charizard"];
Enter fullscreen mode Exit fullscreen mode

If we change the data type, you get type error.

// change array data type
const pokemon: string[] = ["pikachu", "Raichu", false];
Enter fullscreen mode Exit fullscreen mode

This is type error message.

typescript.ts:80:49 - error TS2322: Type 'boolean' is not assignable to type 'string'.

80 const pokemon: string[] = ["pikachu", "Raichu", false];
Enter fullscreen mode Exit fullscreen mode

This is so useful and powerful because we do not have to take care of data type of each array elements. By the way, I want to show you another way of expression. This is the same as above code. It looks like this.

// defined array with another way.
const pokemon: Array<string> = ["pikachu", "Raichu", "Charizard"];
Enter fullscreen mode Exit fullscreen mode

As next data type, I will show you generics data type. This is general data type. After we define generics data type, we can define it. Sample code is like this.

// defined array with generics data type.
type Pokemon<T> = T[];
// After defined generics type, we can define specific data type.
const pokemon: Pokemon<string> = ["pikachu", "Raichu", "Charizard"];

// Above code is the same as this.
const pokemon: string[] = ["pikachu", "Raichu", "Charizard"];
Enter fullscreen mode Exit fullscreen mode

We can define some data type with generics data type.
This is not good sample but easy to understand how to use generics data type. Sample is like this.

// defined array with generics data type.
type Pokemon<T> = T[];
// After defined generics type, we can define specific data type.
const pokemon01: Pokemon<string> = ["pikachu", "Raichu", "Charizard"];
const pokemon02: Pokemon<number> = [6, 14, 16];
const pokemon03: Pokemon<boolean> = [true, true, false];
Enter fullscreen mode Exit fullscreen mode

What is union?

If you want to use union data type, you can define multiple data type. Please look at this sample code.

let pokemon: (string | number) = "pikachu";  // OK
pokemon = 6; 
Enter fullscreen mode Exit fullscreen mode

This code works correctly because pokemon variable can take string or number data types. But this case is wrong.

let pokemon: (string | number) = "pikachu";
pokemon = 6;
pokemon = false;      // NG
Enter fullscreen mode Exit fullscreen mode

Because pokemon variable does not take boolean data type and get complied error. If we want to create an array including multiple data type, of course we can use this union data type. This is the sample code.

// define data type with array and union
let pokemon: (string | number)[] = ["pikachu", "Raichu", 6, 14];
Enter fullscreen mode Exit fullscreen mode

This code is correctly.
But if we add the another data type, we get type error like this.

// define data type with array and union
let pokemon: (string | number)[] = ["pikachu", "Raichu", 6, 14, false];
Enter fullscreen mode Exit fullscreen mode

This is type error message.

typescript.ts:105:65 - error TS2322: Type 'boolean' is not assignable to type 'string | number'.

105 let pokemon: (string | number)[] = ["pikachu", "Raichu", 6, 14, false];
Enter fullscreen mode Exit fullscreen mode

If you want to add multiple data type to the array, you can use this union data type.

What is tupple

Tupple is so strict data type.
Beginning, you can check this code.

let pokemon: [string, number] = ["pikachu", 6];
Enter fullscreen mode Exit fullscreen mode

This code works well. This tupple data type allows only two elements and string and number.
I will show you some wrong case below.


typescript.ts:109:36 - error TS2322: Type 'number' is not assignable to type 'string'.

109 let pokemon02: [string, number] = [6, "pikachu"];      // NG
                                       ~

typescript.ts:109:39 - error TS2322: Type 'string' is not assignable to type 'number'.

109 let pokemon02: [string, number] = [6, "pikachu"];      // NG
                                          ~~~~~~~~~

typescript.ts:110:47 - error TS2322: Type 'string' is not assignable to type 'number'.

110 let pokemon03: [string, number] = ["pikachu", "text"]; // NG
                                                  ~~~~~~

typescript.ts:111:5 - error TS2322: Type '[string, number, number]' is not assignable to type '[string, number]'.
  Source has 3 element(s) but target allows only 2.

111 let pokemon04: [string, number] = ["pikachu", 6, 14];  // NG
Enter fullscreen mode Exit fullscreen mode

Tupple is so strict data type. But it is easy to understand what purpose is this array. It means that the array take only two elements. First, value of string data type. Second, value of number data type.

Conclusion

In this article, I wrote that basic data type of TypeScript.
If you learn typescript, you can check npm packages created by typescript but also write readable and maintained codes.
If you belong to the companies, you know many codes exists there. So, you have to read a lot of codes and understand that. TypeScript helps us understand codes!

This article is just basic knowledge of typescript.
I am planning to write new posts about more typescript data type or React with typescript.
If you are interested in this article, please comment to me!

Thank your for taking your time to read this article.

Top comments (17)

Collapse
 
matjones profile image
Mat Jones

Good article dude. TypeScript is awesome. Basically, TypeScript prevents you from using things the wrong way, at compile time, which is one of its greatest strengths. Especially when vanilla JavaScript has such a wacky type system.

Collapse
 
jamesthomson profile image
James Thomson

It also plays nicely with most IDE's so Intellisense is much more valuable, especially in very large codebases.

Collapse
 
0815fips profile image
0815fips

You can configure your jsconfig.js properly, add JSDoc and *.d.ts files to be as safe as in TS.

Collapse
 
joelbonetr profile image
JoelBonetR 🥇

@matjones @jamesthomson @rammina
We all can agree that TS is a must for a couple of things but did you know that you can use TS in two different ways? Check this out 😄

Collapse
 
kooiinc profile image
KooiInc

I have been programming java-/ecmascript (ES) for 28 years now and never felt the need to use (the hassle of) TypeScript.

It's relatively easy to check the input for a function, e.g. by contract:

function fooContract(a, b) {
  return  a?.constructor === Number && 
     b?.constructor === Number;
}

function foo(a, b) {
  if (fooContract(a, b)) {
    return a + b;
  }

  throw new TypeError(`function foo => expected 2 Numbers`);
}

foo("40", 2); //=> TypeError
foo(32); //=> TypeError
foo(40, 2); //=> 42
Enter fullscreen mode Exit fullscreen mode

To check the type of (nearly) everything in ES, I deviced a small module.

Collapse
 
rammina profile image
Rammina

Great introduction to Typescript! It is not only informative, but also cleanly formatted in a way that beginners can understand.

I can definitely agree with your points, Typescript makes coding less punishing, especially in a larger project. I just love the type safety that it gives you as well as the amazing IntelliSense. While there is boilerplate, it makes up for it by reducing mistakes and bugs, as well as improving code quality.

However, Typescript has downsides, which I discussed here:
dev.to/rammina/downsides-of-typesc...

I hope it will help people when they think about when NOT to use Typescript.

Collapse
 
caleb_whittaker profile image
Caleb Whittaker

That was a very concise article and well formatted for beginners such as myself. I've been learning to code with JavaScript for about a year now and the amount of times that I've received type errors or other bugs that took me longer than I'd like to admit to find makes me wish I had started to learn TypeScript sooner.

Collapse
 
ananddevspace profile image
Anand

Nice Article, Keep Writing 👏

Collapse
 
mehrdadarman profile image
Mehrdad Arman

Nice article... short and useful

Collapse
 
raimundo82 profile image
João Raimundo

Jsdoc solves the motivation problem. By the way, it's bad practice to name a function that adds two args pikachu

Collapse
 
imran2part profile image
imran2part

Nice article please write for us ts with react

Collapse
 
jamesli2021 profile image
jamesli2021 • Edited

Good student pickup TypeScript. Go language and TypeScript are perfect since both feels similar.