Typescript in brief

Typescript in brief

Typescript is not understood by the browser but what the browser does understand is javascript. So basically Ts is a superset of Js which wraps up Js thus providing extra functionality like strict type checking. Converting Ts into js happens behind the scene n this is what code transpiling known as. Thus, reducing the number of bugs.

Types by Inference

TypeScript knows the JavaScript language and will generate types for you in many cases. For example in creating a variable and assigning it to a particular value, TypeScript will use the value as its type.

let helloWorld = "Hello World";

let helloWorld: string

Defining Types

For example, to create an object with an inferred type which includes name: string and id: number, you can write:

const user = { name: "Hayes", id: 0, };

You can explicitly describe this object’s shape using an interface declaration:

interface User { name: string; id: number; }

You can then declare that a JavaScript object conforms to the shape of your new interface by using syntax like : TypeName after a variable declaration:

const user: User = { name: "Hayes", id: 0, };

If you provide an object that doesn’t match the interface you have provided, TypeScript will warn you:

interface User { name: string; id: number; }

const user: User = { username: "Hayes", Type '{ username: string; id: number; }' is not assignable to type 'User'. Object literal may only specify known properties, and 'username' does not exist in type 'User'. id: 0, };

Since JavaScript supports classes and object-oriented programming, so does TypeScript. You can use an interface declaration with classes:

interface User { name: string; id: number; }

class UserAccount { name: string; id: number;

constructor(name: string, id: number) { this.name = name; this.id = id; } }

const user: User = new UserAccount("Murphy", 1);