What is TypeScript?
The goal of TypeScript is to help catch common errors as we type the code through a type system and to make JavaScript development more efficient. The major concern of JavaScript is that it wasn’t initially meant for building enterprise-level applications. And that’s where TypeScript steps in. Related to JS in terms of syntax and semantics, TS brings a number of additional tools that increase productivity and facilitate the creation of large codebases. It is worth mentioning that in the end Typescript compiles to JavaScript, so the final code can run on any environment which supports JS. It can be both client-side (ReactJs) and server-side (Node.js).
TypeScript Compiler Configuration : TypeScript compiler uses tsconfig.json to get configuration options for generating JavaScript code from TypeScript source-code. To compile TypeScript code, the compiler searches for configurations located in tsconfig.json.
Points to note:-
- The tsconfig.json is generally put in the root folder of the project.
- It provides the compiler options required to compile the project.
Creating tsconfig.json :
Before we start using TypeScript, make sure we have installed it. To use conveniently, install it as global or dev dependency so that we can use tsc command from console window. Then use 'tsc --init' command to create tsconfig.json file in your project’s root folder. Steps :
- Install typescript locally (as dev dependency) using npm
- Check the TS version
- Create the tsconfig.json file.
Target in tsconfig.json
The "target" property is used to specify the JavaScript version the TypeScript code will eventually compile into.
Modern browsers support all ES6 features, so ES6 is a good choice. We might choose to set a lower target if our code is deployed to older environments, or a higher target if our code is guaranteed to run in latest environments. The target setting changes which JS features are down leveled and which are left intact. For example, an arrow function () =>
this will be turned into an equivalent function expression if target is ES5 or lower.
Why do I need static typing? Why do I need TypeScript at all?
- Type safety: In Typescript, we can explicitly define function parameters types. Therefore, it prevents us from passing the wrong type of argument to the function as shown in the example below:
TypeScript is more reliable : In contrast to JavaScript, TypeScript code is more reliable. This enables developers to evade errors and do rewrites much easier. Types invalidate most of the silly errors that can sneak into JavaScript codebases, and create a quick feedback loop to fix all the little mistakes when writing new code and refactoring.
Improves code quality: One of the biggest benefits of TypeScript is that it can offload a huge amount of effort when coding since it will alert when the specified type is not matching. This means the user essentially let the compiler tells when one have made a mistake. The user can immediately make the necessary adjustment right then and there, instead of waiting until the code runs.
Typescript gives a great IDE Support: Mouse hover support, code auto-completion, real-time type checking, easier code refractor
TypeScript’s type system is Turing complete : Turing completeness is being achieved by combining mapped types, recursive type definitions, accessing member types through index types and the fact that one can create types of arbitrary size. In particular, the following device enables Turing completeness:
type MyFunc<TArg> = {
"true": TrueExpr<MyFunction, TArg>,
"false": FalseExpr<MyFunc, TArg>
}[Test<MyFunc, TArg>];
(with TrueExpr, FalseExpr and Test being suitable types.)
Therefore: TypeScript is suitable for developers who want to create readable code that is neat and clean .Not to mention the various live-bugs checking, and static typing of TypeScript.However, TypeScript, like JavaScript, is not supported by all web browsers. Since TypeScript is a superset of JavaScript, we can use all JavaScript libraries and code that we want in your TypeScript code. just switch the file extension to .ts from .js.
HOW TO CREATE CUSTOM TYPES THROUGH INTERFACES AND TYPES?
Why do we need custom types?
In cases where programs have complex data structures, using TypeScript’s basic types may not completely describe the data structures you are using. In these cases, declaring your own type will help you address the complexity. Assume, a function always returns data in a certain format, and uses an API to get that data. If the API returns data in the wrong format, we probably don't want the wrongly formatted data to end up in our code where it could cause issues and errors. In such a case, we might ask that the return of a function satisfies to a certain type. Therefore, we define our own types to ensure the type checker validates the data structures specific to our project.
How do we need custom types ?
1. Syntax – Custom Types
In TypeScript, the syntax for creating custom types is to use the type keyword followed by the type name and then an assignment to a {} block with the type properties.
If we give something the type Programmer, then we expect it to have at least a ‘name’ and ‘knownFor’, and an optional value (‘birthYear’), which does not have to be given. As we can see, having a question (?) mark in our type denotes that this property is optional. ‘ada’ is a variable of the type ‘Programmer’
2. Extension of Custom Types
In the above example, the type ‘programmerDetails’ will have everything ‘Programmer’ has, plus a required added attribute called ‘location’.
Intersection Types
Intersection allows us to combine multiple types into a single one type. To create an intersection type, we have to use the & keyword:
We can create a new intersection type combining two interfaces, but not the other way around, i.e., create an interface combining two types.
Union Types
Union types allow us to create a new type that can have a value of one or a few more types. To create a union type, we have to use the | keyword.
Similar to intersections, we can create a new union type combining two interfaces, for example, but not the other way around.
Using Interfaces instead ? Everything we've spoken about so far has been using the type keyword, but we can do the same stuff using the interface keyword instead.
the type ‘programmerDetails’ must include all properties and methods of interface ‘Programmer’ has, plus a required added attribute called ‘location’.
Extends and implements
In TypeScript, we can easily extend and implement interfaces which is not possible with types . Interfaces in TypeScript can extend classes, this is an extremely useful concept in a more object-oriented way of programming.
In the above example, the interface ‘NewCar’ is extending the properties of class ‘Car’.
Declaration Merging
One thing that’s possible to do with interfaces but are not with types is declaration merging. Declaration merging happens when the TypeScript compiler merges two or more interfaces that share the same name into only one declaration. Let’s consider the previous example of ‘Programmer’ interface:
TypeScript will automatically merge both interfaces declarations into one, so when we use this “Programmer” interface, we’ll have both properties.Declaration merging does not work with types. If we try to create two types with the same names, but with different properties, TypeScript would still throw us an error.