Connect with us

Get more updates and further details about your project right in your mailbox.

Thank you!
Oops! Something went wrong while submitting the form.
August 17, 2023

Typescript vs Javascript

The best time to establish protocols with your clients is when you onboard them.

Heading

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse varius enim in eros elementum tristique. Duis cursus, mi quis viverra ornare, eros dolor interdum nulla, ut commodo diam libero vitae erat. Aenean faucibus nibh et justo cursus id rutrum lorem imperdiet. Nunc ut sem vitae risus tristique posuere.

Introduction

JavaScript was initially developed as a frontend language, It can run only on web browsers. Later in 2009 NodeJS introduced its JavaScript runtime environment so that JS can run stand-alone without web browsers. This was a big step in the evolution of JS but it did not have full fledged OOPS support for features such as prototyping, types and interfaces.

JS was an ideal option for small sized projects. Even though it was possible to do bigger projects with JS, it was not developer friendly. To overcome this in 2012 Microsoft came up with TypeScript which is a superset of JavaScript. Code written in TypeScript is converted into Plain JavaScript code and then gets executed.

It has code navigation, bug prevention and optional static type annotation/static typing. It also supports interfaces, sub-interfaces, classes, subclasses and some additional features for functions.

How To install TypeScript:

CMD: npm install -g typescript

The above command will install typescript globally in your machine.

How Type Safety Works in TS:

In TS code we declared an identifier named “firstName” with Type annotation of string and we have given a value with data type of string and then we try to mutate its value to a number. So it shows an error: “Type ‘number’ is not assignable to type ‘string’.” This makes it easy to maintain the data type of the value.

All JS primitive data types are supported by TS including boolean, string, number, undefined, null, any, unknown, never, void, bigint and symbol.

Note: “any” is a special data-type, also the super data-type of all data types. If a variable is declared with any data type then we can assign any type of value to that variable. This should not be used unnecessarily as it destroys the purpose of using TypeScript in the first place.

Rules to declare Identifier names and Type annotation in TS

  • All declarations in JS: var, let and const are supported in TS and its scope behaviour is also similar
  • Identifier naming rules is the same as JS
  • Type annotation can be declared as follows
    var [identifiers] : [type annotation] = value (or)
    var [identifiers] = value as [type annotation] (or)
    var [identifiers] : [type annotation]

How TS provides Type Safety:

In the above two images we are trying to fetch the value of attribute ‘id’. At first we get an empty array and at next attempt we get the record. This is due to type annotation. We have a function called ‘employeeFilterWithId’ which filters the employee list based on the passed id. In the first example, we pass a value with type number and in the second example we are sending a string. The result is stored in an array of objects ‘employeeDetailsList’ which has different values. Let’s see how we can overcome this issue with TS.

Interfaces in TS:

Interface is a structure that defines the contract in your application. It defines the syntax for classes to follow. Classes that are derived from an interface must follow the structure provided by their interface. The TypeScript compiler does not convert the interface to JavaScript. It uses interfaces for type checking. This is also known as “duck typing” or “structural subtyping”.

Interface example in TS:

interface employeeDetail:{

name: string,

id: string,

role: string,

dateOfJoining?: number

}

Here the interface name is employeeDetail and the structure is as mentioned. We can use optional values by specifying ‘?’ after the variable name.

Here we have an interface for the objects inside the array. If we try to add a property which is not present in the interface, it shows an error. We can also specify type annotation in the function arguments, which helps us send the correct type of parameters during function invocation.

Using ‘TypedPropertyDescriptor’ we restrict and change the interface behaviour

Syntax : var [identifiers] : <TypedPropertyDescriptor><T>

For example,

var [identifiers]: Readonly<employeeDetailList[]>

In cases where the value should not get mutated, readonly can be used before the type annotation.

There are different kind of TypedPropertyDescriptor in TypeScript they are ArrayLike, Partial, Required, Readonly, Pick, Record, Exclude, Extract, Omit, NonNullable, Parameters,ConstructorParameters, ReturnType,InstanceType, Uppercase, Lowercase, Capitalize, Uncapitalize, This, Type these all will change the behaviour of the interface.

Function Invocation TS vs JS

During function invocation, if you fail to send a parameter’s value it will throw an error that ‘Expected 1 argument but got 0’. This helps us to easily find an error whereas in JS it would take an argument value of undefined and it would execute without displaying any error.

In larger projects we can also maintain type interfaces in separate files and use export and import to use it wherever needed.

Pros of using TypeScript:

  • TypeScript highlights errors that will occur during compilation time whereas JavaScript fails to do so.
  • Using Type annotation we can handle data types of values easily.
  • Type inference/Implicit typing are performed by TypeScript, which means developers don’t need to provide types where the compiler can find them on its own.
  • TS helps in code structuring.
  • Typescript is more developer friendly in the long term.

Cons of using Typescript:

  • TS takes longer to compile.
  • When using a third party library, there needs to be a definition file, which may not always be available.
  • When utilizing a 3rd party library with NPM that does not have proper documentation, we would have to explore and find ways to implement them in TS.
  • We can’t easily switch existing projects from JS to TS even though both use the same compiler because TypeScript syntax differs from JS.

Conclusion:

TypeScript is a superset of Javascript so we can’t compare or consider it as a competitor language. Both have some Pros and Cons. TypeScript is suitable for larger projects with sizeable teams as it has better readability.Although JavaScript is not a comprehensive programming language, it can be used for smaller projects and it has more support and package compared to TS

CodeStax.Ai
Profile
August 7, 2023
-
6
min read
Subscribe to our newsletter
Thank you! Your submission has been received!
Oops! Something went wrong while submitting the form.
Share this article:

More articles