loading...
Cover image for TypeScript Basics - A Definitive Guide

TypeScript Basics - A Definitive Guide

ganeshmani profile image GaneshMani Originally published at cloudnweb.dev ・7 min read

In this article, we will learn some basics of typescript which helps you to develop javascript application in a better way. TypeScript Basics - A Definitive Guide

What is TypeScript and why we need it?

So, before diving into the concepts of typescript. we should know what is typescript and why it is needed.

Firstly, TypeScript is a superset of JavaScript which primarily provides optional static typing, classes and interfaces. One of the big benefits is to enable IDEs to provide a richer environment for spotting common errors as you type the code.

As a Javascript developer, there is one thing that we miss when compared with other languages such as Java,C#. that is, TypeCheck.

languages like java checks the type of defined variable in the compile time itself unlike javascript. it helps to solve lot of bugs in the compile time itself

To solve this problem in javascript. TypeScript is introduced.

Setting up TypeScript

TypeScript is only for development purpose. Since, browser/JS engine doesn't understand anything except javascript.

So, we need to compile the typescript to javascript before running it the server/browser.

Here's an article explaining the complete setup and production deployment of typescript in Node.js Application.

Understanding Types

Types are not a new in javascript. javascript already have dynamic types. they are,

  • Undefined
  • Null
  • Boolean
  • Number
  • String
  • Symbol
  • Object

But, these types in javascript are dynamic. javascript checks the type of variables in run time.

Instead of checking the type in runtime, Typescript check that on compile time. static type predicts the value of dynamic types.

Basic Static Types

String

it is a textual data surrounded by single or double quotes

const message: string = 'hello world';
console.log(message);

Boolean

this type represents the boolean value which is either true or false

const isType: boolean = false
console.log(isType);

Number

this type represents the integer value in the variable. there are four type of number literals supported in the number type

const age: number = 40;
console.log(age)

Array

there are two ways to type check an array in Typescript. first way is to add [] to the element type

let newArray: string[] = ["one", "two", "three"]
console.log(newArray)

second way is to use the keyword Array with the type,

let newArray: Array<string> = ["one", "two", "three"]
console.log(newArray)

Enum

enums allow us to declare a set of named constants i.e. a collection of related values that can be numeric or string values.

Mainly, there are three types of enum,

  • Numeric Enum
  • String Enum
  • Heterogenous Enum
enum Status {
    Inactive = 0,
    active = 1
}

console.log(Status.active)
enum Status {
    Inactive = "INACTIVE",
    active = "ACTIVE"
}

console.log(Status.active)

Any

if the variable type is not known and we don't want the type checker for the particular variable, then the type of any can be used.

let checkValue: any = true

checkValue = "Check";
checkValue = 14

void

void is used when there is no return value in the function. if there is no return data type for a function, void is used.

const LogIt = (): void => {
    console.log("log")
}

Type Inference

Mainly, TypeScript has a feature which identifies the type of variable from the value assigned to it. it is called Type Inference.

For example,

let userName = "String"

TypeScript identifies the variable userName as a string from it's value. and throw error if you assign a type number to it.

This concept is called as Type Inference.

Interface

Firstly, interface in Typescript is a way to check the type of an object. if we want to check the type of values in group. Interface is the best choice.

For Example,

interface userData {
    name: string,
    age : number
}

let AddUserDetails = ({ name, age }: userData): void => {
    let arr = [];

    arr.push({
        name,
        age
    })
}

AddUserDetails({ name : "Ganesh",age : 25});

Here, we have a function called AddUserDetails which takes two arguments such as name and age.

To check the Type of Both arguments, we need interface. So, we created an interface userData and typecheck it.

if we pass first value as number, it will throw an error. Alternatively, we can define type of any to pass value.

Generics

In TypeScript, Generics enables you to create reusable code components that work with a number of types instead of a single type. For Example,


const createNewArray = (value: string): Array<string> => {
    let output : Array<string> = [];

    output.push(value);

    return output;
}

Here, function createNewArray takes an argument with type string and return an array with that value. but what if we want to create an array with type number.

above implementation with throw an compilation error on that scenario. we can solve this problem using Generic.


const createNewArray = <T>(value: T): Array<T> => {
    let output : Array<T> = [];

    output.push(value);

    return output;
}

let val = createNewArray<string>("fdfsd");

console.log(val)

The above example has a generic type T that corresponds to the type of the argument that is passed to the createNewArray function.

T is a naming convention that represents string here, because we are passing Type string while we call the function.

If we change the type to number while we call function/class. it will take the type dynamically. that's the beauty of Generics

there are different way to implement the generics, we can implment it in Interface, Class and Type Generics.

Conclusion

Honestly, we barely scratched the surface of TypeScript. we will see this concepts in more depth in upcoming articles, until then you can refer some wonderful articles on typescript.

TypeScript Handbook (Official TypeScript docs)

TypeScript Deep Dive (Online TypeScript Guide)

Understanding TypeScript’s Type Annotation (Great introductory TypeScript article)

Posted on by:

ganeshmani profile

GaneshMani

@ganeshmani

Full Stack Engineer. Currently focusing on Javascript, React, GraphQL, and Nodejs.

Discussion

markdown guide
 

Nice one !
I recommand you to use const rather than let if you didn't reassign variable as :

const createNewArray = <T>(value: T): Array<T> => {
    const output : Array<string> = [];

    output.push(value);

    return output;
}

And last tips, you can declare type array as below for an array of string.

const output: string[] = []; // Array of string
const output2: number[]; // Array of number, etc...
 

Sure.. will change it..thanks for the heads up.. :-)

 

I wonder who started that thing with those He-Man images......

 

Me too...but i like that combo... that's why I kept it ..

 

Have you had any experience converting an existing project over to typescript? Is there a way of slowly accomplishing the task or is it an all or nothing route?

 

Typescript allows you to declare type declarations, in which you can create definitions of old code and write new code in TypeScript. Slowly you can even rewrite old code in TypeScript one file at a time, and since TypeScript's output is pure JavaScript, your code can co exist along with old plain JavaScript and New TypeScript generated JavaScript.