JavaScript vs TypeScript: Why TypeScript is Worth Learning

JavaScript vs TypeScript: Why TypeScript is Worth Learning

ยท

10 min read

What is TypeScript?

Hello, I am a student in Pakistan, 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 JavaScript is not as strict in syntax as other languages, it offers more freedom in coding. However, when dealing with a large amount of code in your project, this freedom can sometimes lead to challenges and complexities.

Please look at this code.

// Can you guess the return value?
const sum = (a, b) => {
  return a + b;
}

Can you guess the return value of this code?

I cannot do it because the sum function can take all types of variables like string, number, and so on.

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

JavaScript is a dynamically typed language, which makes coding easier. However, developers need to be careful about the arguments required in a function and the value returned from it. The more you read code, the more you realize this can be stressful.

On the other hand, please take a look at this code.

// Can you guess the return value?
const sum = (a: number, b: number): number => {
  return a + b;
}

This is TypeScript code, which uses static typing. Looking at this, we can easily predict that the sum function will return a number. Understanding code like this is incredibly helpful because companies often have complex codebases. Therefore, it's important to use clear methods that make it easier to read and comprehend code written by others 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

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

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

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;

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

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

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

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 sum = (a, b): number => {
  return a + b;
}
pikachu(2021, 9);

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 sum = (a, b): number => {
                    ~

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

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

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 sum = (a: number, b: number): number => {
  return a + b;
}

or

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

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 objtype{
  name: string,
  age: number,
  skill: string
}
// assign data type to object.
const obj: objtype= {
  name: "jhon",
  age: 6,
  skill: "web development"
}

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 objtype{
  name: string,
  age: number,
  skill: string
}
// assign data type to object.
const obj: objtype= {
  name: "jhon",
  age: "change age",       // change 
  skill: "web development"
}

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 'objtype'

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 obj: {name: string, age: number, skill: string} = {
  name: "jhon",
  age: 6,
  skill: "web developement"
}

Array data type

Array with data type is like this.

// define array data type
const array: string[] = ["Abdullah", "Ali", "Charizard"];

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

// change array data type
const array: string[] = ["Abdullah", "Ali", false];

This is type error message.

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

80 const array: string[] = ["Abdullah", "Ali", false];

This is beneficial as we don't need to manage the data type of individual elements within an array, and here's another way to express the same concept as shown in the code above.

// defined array with another way.
const array: Array<string> = ["Abdullah", "Ali", "Charizard"];

As the next data type, I will demonstrate generics data type, which is a general data type that can be defined after specifying it, with a sample code like this.

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

// Above code is the same as this.
const array: string[] = ["pikachu", "Raichu", "Charizard"];

We can define a data type with generics.
This is not a good sample, but it's easy to understand how to use generics. A sample is like this.

// defined array with generics data type.
type array <T> = T[];
// After defined generics type, we can define specific data type.
const array01: array<string> = ["pikachu", "Raichu", "Charizard"];
const array02: array<number> = [6, 14, 16];
const array03: array<boolean> = [true, true, false];

What is union?

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

let value : (string | number) = "pikachu";  // OK
pokemon = 6;

This code works correctly because the value variable can take a string or number data type. But in this case, it is incorrect.

let value : (string | number) = "pikachu";
pokemon = 6;
pokemon = false;      // NG

Because the value variable does not accept boolean data type, it results in a compilation error. If we intend to create an array that includes multiple data types, we can certainly utilize this union data type. Here is an example code snippet.

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

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 array : (string | number)[] = ["pikachu", "Raichu", 6, 14, false];

This is type error message.

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

105 let array: (string | number)[] = ["pikachu", "Raichu", 6, 14, false];

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

What is tupple

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

let array : [string, number] = ["pikachu", 6];

This code works fine. The tuple data type here only allows two elements: a string and a number. Let me demonstrate some incorrect cases below.


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

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

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

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

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

110 let array03: [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 array04: [string, number] = ["pikachu", 6, 14];  // NG

Tuple is a very strict data type, but it's easy to understand its purpose for this array. It means that the array can only have two elements: first, a value of string data type, and second, a value of number data type.

Conclusion

In this article, I discussed the basic data types in TypeScript. By learning TypeScript, you can review npm packages developed with TypeScript and write clear, maintainable code. In corporate settings, you encounter extensive codebases, requiring thorough code reading and comprehension. TypeScript facilitates code understanding.

This article covers fundamental TypeScript knowledge. I intend to write future posts on additional TypeScript data types or React with TypeScript. If you found this article interesting, please leave a comment!

Thank you for taking the time to read this article.

ย