Type Script — Introduction & Lessons | Vishal Jadhao
What is typescript?
It is a strict syntactical superset of JavaScript and adds optional static typing to the language. TypeScript is designed for the development of large applications and transcompiles to JavaScript.
As javascript is a dynamically typed language and types are evaluated at run time only, invalid type issues may introduce bugs in production and can take time to track down those.
According to StackOverflow’s 2020 Developer Survey, TypeScript is currently the second most loved programming language:
Typescript benefits
1. Catch errors early in development
2. Serves as documentation
Let’s dive into it
Types (number, string, boolean, null, undefined, any, tuple etc…)
TypeScript adds some rule about how different kind of values can be used, below are some basic types along with examples:
Union Types
Occasionally, you’ll run into a situation that expects a parameter either a number or a string, for example
Enum Type
Enums are one of the few features which typescript has, which is not type level extension of javascript. Enums allows developer to define set of named constants, for example
Objects & Functions
As objects are used to group and pass around data, we can use Object types.
function arguments and returned type can also be typed, for example
Interfaces
An interface is a blueprint of an entity, it defines a syntax that entity must adhere to. Interface defines properties, methods and events. Use interfaces for complex data types.
Classes
A class in terms of OOP is a blueprint for creating objects. Typescript gives built in support for this concept called class. Typescript gets this feature from ES6.
Type Assertion
It is similar to type casting in other languages like C# and Java. However, unlike C# and Java, there is no runtime effect of type assertion in TypeScript. It is merely a way to let the TypeScript compiler know the type of a variable.
Generics
Generics offer a way to create reusable components. Generics provide a way to make components work with any data type and not restrict to one data type.
React with TypeScript
There are couple of ways you can add type checking for your react code, you can use flow, proptypes, jsdocs and TypeScript.
Adding typescript to your CRA:
npx create-react-app — template typescript projectName
Configuration File: tsconfig.json
Below is sample react functional component with typescript
Our Aim is to create robust code, not messy, unreadable or complex.
Hope you enjoyed! Give a thumbs up. Thank you!