TypeScript 101: Core Types

TypeScript 101: Core Types

ยท

3 min read

Let's Start

As we said in the introduction, Typescript is a Superset of JavaScript which means that it is still JavaScript but with static Types e other features.

Some of the features:

Types for free bug code and cleaner code,

Adds of Interfaces and Generics,

Add of Decorators ,

Comes with a rich configuration options file.

if you didn't know, JavaScript is a Dynamic typing language, so when you assign a value to a variable you don't need to specify what type is the variable, JavaScript engine infers the type of the variable at run time.

Typescript instead is a static type language, if you don't specify the type, yes it will infer it , not like JavaScript at run time but before in development so that when you compile your code if there is a bug you can see it before goes out in the browser and so No space for Bugs

This is one of the best feature of Typescript this layer of static types where if not assigned and there is a bug you can't compile the code so it never goes out of your development environment.

That's cool and safe but the inference works only for the Core Types of Typescript.

What are the core types?

The core Types in TypeScript are:

String,

Number

Boolean.

An example:

//Type Inference
// declaring this variable Typescript infers that this myString variable will be a string type
let myString="hello"

//if we change the value Type it will yell at us

myString=20 // In the editor you should have the red string under myString.

TypeError.jpg

Now, You can be explicit even for variables and so specify the type for all of them like so :


let myString:string = "Hello world"

let myNumber:number = 10

let myboolean:boolean = True

But I would suggest you to let TypeScript infer the type of the variables and focused on specify types for objects, arrays, functions etc...

Now that you have a general idea of what Typescript bring to JavaScript we can install it on out system and start to talk about other features.

To install TypeScript in you system, open your terminal and type:

npm install -g typescript

I assume that you already have installed Node, if not just follow The link https://nodejs.org/en/ to install it.

if you want to create a file to play with it for the moment, the extension of your file with TypeScript will be .ts so **for example index.ts that once transpilled to JavaScript it will create a second file called index.js** and this file will be compiled to the browser.

To transpile the index.ts file just run this command in your terminal

tsc index.ts

Conclusion

Great I hope you got some knowledge from this first part on the Typescript series, every post will be not to long, that's because Typescript is a bit hard to grasp a the beginning and so better have short post easy to digest and then move on to the next one.

Thanks for reading it and if you want to ask me something just leave a comment and I will answer your question.๐Ÿ‘‹๐Ÿป