Uncategorized

TypeScript

TypeScript is an open source superset of JavaScript that is compiled into plain JavaScript. It provides static type checking at compile time.

TypeScript was designed to prevent issues that typically occur in JavaScript because of the lack of type checking. It also adds features like Interfaces, Generics, Namespaces, Null Checking and Access Modifiers.

Deep dive into TypeScript

Although Javascript code is valid Typescript code it may not always be processable by the TypeScript compiler.

Example:

let myStr = 'a';
myStr = 5; // error TS2322. Type '5' is not assignable to type 'string'

Let us look at some of the features of TypeScript in depth.

Interfaces

Interface is a core principal of TypeScript that focuses on verifying the shape that values have. Using an interface, we can define what a function param needs to be passed, what a REST API response should expect etc.

We can also have optional properties in an interface. If the property can only be set once, we can mark the property as readonly.

interface ShapeConfig {
   readonly borderColor: string;
   width: number;
   height?: number; //optional property
}
function createShape(config: ShapeConfig)" {borderColor: string; area: number}{
  let newShape = {color: config.borderColor, width: config.width};
  if (!config.height){
     config.height = config.width;
 }
 newShape.area = config.width * config.width;
 return newShape;
}

let mySquare = createSquare({borderColor:"black"});

Interfaces can also be used to describe a function type. We define the call signature in the interface.

interface callFunc {
 (source: string, token: string): boolean;
}

Generics

Generics are similar to templates in C++. Generics allow methods to operate on objects of various types while providing compile time type safety. It allows us to define reusable components.

function mathutil<T>(arg: T): T {
   return arg;
}

let out = mathutil<float>(3.0);

Null Checking

Typescript has two special types: Null and Undefined that have values null and undefined respectively. In JavScript we could assign any variable as null or undefined. We could not specifically exclude them and they caused a lot of errors.

–strictNullchecks switches to a new strict null checking mode. In this mode null and undefined are not in the domain of every type and are only assignable to themselves.

// Compiled with --strictNullchecks
let x: number;
let y: number|undefined;
let z: number|null|undefined

x= undefined; // Error
y= undefined; //Ok
y= null; //Error
z= null; //Ok

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s