Introduction to Typescript
TypeScript is an open-source programming language developed by Microsoft. It is an extension of JavaScript that allows you to write more complex JavaScript code without worrying about common data type errors.
TypeScript supports additional features such as static typing, declaring types for variables and classes, making it easier, more efficient, and easier to maintain when developing JavaScript applications.
1. Static typing
In TypeScript, static typing allows you to define the data type of variables, functions, objects, and other components in the program. When you declare a variable with a specific data type, TypeScript will give you an error if you assign a value that does not match that data type.
For example, if you declare a variable with a data type of integer, TypeScript will give you an error if you assign a string value to that variable.
let myNum: number;
// OK
myNum = 42;
// Error: Cannot assign type 'string' to type 'number'
myNum = "Hello world!";
const myNum: number = 10;
// or
const myNum = 10;
function multiply(a: number, b: number): number {
return a * b;
}
// OK
add(1,2);
// Error
add(2,"3");
In the example above, we have a multiply
function that can take two parameters as numbers and return a number. By using static data types in TypeScript, we clearly specify that the data type of the two parameters a
and b
is a number
, and the data type of the return value is also a number
. If we try to pass a string ("3"
) to the parameter b
, TypeScript will report a compilation error due to the incompatible data type, helping us detect errors before running the program.
2. Support for new features of ES6 and ES7
TypeScript provides support for many new features of ES6 and ES7 versions, making web application development easier.
1. Let and Const
TypeScript supports variable declaration using let
and const
, making variable management easier.
let a: number = 1;
const b: string = 'Hello world!';
2. Arrow Function
TypeScript allows using arrow function syntax () => {}
to define functions, making the code shorter and more concise.
function multiply(a: number, b: number): number {
return a * b;
}
// arrow function
const multiple = (a: number, b: number): number => (a * b);
3. Template Literals
Typescript supports using template literals to create strings that can be combined with JavaScript expressions.
let isRed: boolean = true;
const text = `${isRed ? 'Red' : 'Blue'}`
4. Destructuring
TypeScript supports the destructuring of values in an array or object.
const [a, b] = [1, 2];
console.log(a, b) // 1 2
const [a, b, ...c] = [1, 2, 3, 4, 5]
console.log(a, b, c) ; //1, 2, [3, 4, 5]
const user = { name: "John", age: 20 };
const { name, age } = name;
console.log(name) // John
console.log(age) // 20
5. Spread Operator
TypeScript supports using the spread operator (...
) to pass parameters or copy arrays and objects.
const a = [1, 2, 3];
const b = [4, 5, 6];
const c = [...a, ...b];
console.log(c); // [1, 2, 3, 4, 5, 6]
const x = { name: "John" };
const y = { age: 20 };
const z = { ...x, ...y };
console.log(z); // { name: "John", age: 20 }
6. For-of Loop
TypeScript allows using the for-of loop to iterate through the elements in an array.
const a = [1, 2, 3, 4, 5, 6];
for (const i = 0; i < a.length - 1; i++) { }
for (const i in a) { }
for (const i of a) { }
7. Async/Await
TypeScript supports using the async/await
syntax to handle asynchronous operations.
async function getPosts() {
const res = await fetch('');
const data = res.json();
return data;
}
8. Optional Chaining
TypeScript provides support for optional chaining (?.
) to check whether a property or method exists before accessing it.
const user = { name: "John", age: 20 };
const name = user?.name;
const address = user?.address || "Unknown";
console.log(name); // John
console.log(address); // Unknown
9. Nullish Coalescing
TypeScript provides support for nullish coalescing (??
) to handle null or undefined values in comparison expressions.
const x = null;
const y = undefined;
const z = 0;
const result1 = x ?? 10;
console.log(result1); // output: 10
const result2 = y ?? 20;
console.log(result2); // output: 20
const result3 = z ?? 30;
console.log(result3); // output: 0
3. Modules
Typescript supports popular module types such as CommonJS
, AMD
, SystemJS
, ES6
, and UMD
. Modules help to break down the source code into independent parts that are easy to manage and reuse. By using modules, we can import/export objects, functions, and variables between files or between different applications.
// math.ts
export function add(a: number, b: number): number {
return a + b;
}
Then, in another file, we can import the add function from the math
module like this:
import { add } from './math';
const result = add(2, 3);
console.log(result); // 5
Typescript also allows the use of the namespace
concept to create modules
with multiple components. For example, we can declare a namespace
named utils in a file called utils.ts
as follows:
// utils.ts
namespace utils {
export function add(a: number, b: number): number {
return a + b;
}
export function multiply(a: number, b: number): number {
return a * b;
}
}
export default utils;
Then, we can import and use the add and multiply
functions in another file as follows:
import utils from './utils';
const sum = utils.add(2, 3);
const product = utils.multiply(2, 3);
console.log(sum, product); // 5 6
With support for popular modules, Typescript makes application development easier and more organized.
4. The feature of detecting compile-time errors
The feature of detecting compile-time errors is one of the prominent features of TypeScript. TypeScript checks the source code during compilation to detect potential errors before executing the code. This helps to detect errors such as mismatched data types, using variables that have not been declared, or using non-existent methods before the application is run.
When a compile-time error occurs, TypeScript provides detailed error messages, including the error location, data type information, and debug information. This makes it easier and quicker to identify and fix errors.
function add(a: number, b: number) {
return a + b + 'test'; // error TS2365: Operator '+' cannot be applied to types 'number' and 'string'.
}
const result = add(2, 3);
console.log(result);
5. Inheritance
Inheritance allows a child class to inherit properties and methods from a parent class. The child class can use the properties and methods of the parent class, as well as define its own properties and methods.
To inherit from a parent class, we use the extends
keyword. For example, the following code defines a Person class and an Employee
class that inherits from Person
:
class Person {
name: string;
age: number;
constructor(name: string, age: number) {
this.name = name;
this.age = age;
}
sayHello() {
console.log(`Hello, my name is ${this.name} and I am ${this.age} years old.`);
}
}
class Employee extends Person {
employeeId: number;
constructor(name: string, age: number, employeeId: number) {
super(name, age);
this.employeeId = employeeId;
}
getEmployeeId() {
console.log(`My employee ID is ${this.employeeId}`);
}
}
In this example, the Employee
class inherits from the Person
class using the extends
keyword. The Employee
class can use the properties and methods of the Person
class, including name
, age
, and sayHello
. In addition, the Employee
class also defines its own property employeeId
and a method getEmployeeId
.
When we create an object of the Employee
class, it can use both the methods and properties of both the Person
and Employee
classes, as shown in the following code:
const employee = new Employee('John Doe', 30, 1234);
employee.sayHello(); // Output: Hello, my name is John Doe and I am 30 years old.
employee.getEmployeeId(); // Output: My employee ID is 1234.
Inheritance is an important feature of object-oriented programming (OOP) and makes application development easier by reusing source code and reducing repetition in class definitions.
6. Library
TypeScript supports standard JavaScript libraries such as the DOM
, Fetch API
, and other features.
In addition, the TypeScript community has also developed many open-source libraries that can make application development easier, such as:
React: Facebook's React library has been rewritten in TypeScript and supports static data types.
Angular: Google's Angular framework is designed to work well with TypeScript.
Vue.js: The Vue.js library also supports TypeScript.
Lodash: The Lodash library provides many utility functions for working with arrays, strings, numbers, and objects.
Moment.js: The Moment.js library helps to handle dates and times in JavaScript and supports TypeScript.
RxJS: The RxJS library helps to handle asynchronous data streams and also supports TypeScript.
Overall, the rich library of TypeScript along with other well-known open-source libraries allows developers to easily develop complex and powerful applications.
7. Scalability
TypeScript has high extensibility, allowing developers to customize and extend the language according to their needs. This is demonstrated through the following features:
1. Type extension declaration
TypeScript allows programmers to declare type extensions for the libraries or modules they use. This helps to make error detection during development more accurate.
Suppose you are using a third-party library, such as moment.js
, to handle dates and times in your application. However, TypeScript does not have a default data type for moment.js
. To solve this problem, you can declare a type extension for moment.js
as follows:
declare module "moment" {
interface Moment {
// Declare a data type for the isLeapYear method
isLeapYear(): boolean;
}
}
We have declared a new data type for moment.js
using the keywords declare
and module "moment"
. Then, we have extended the Moment
interface of moment.js
to add a new method, isLeapYear
, which returns a boolean
data type.
After declaring this type extension, TypeScript will understand that moment().isLeapYear()
is a valid method and can determine its return data type. This helps to make error detection during development more accurate.
2. Decorator
Decorator is a feature in TypeScript that allows developers to add additional functionality to classes, methods, or properties. It is a feature introduced in ECMAScript 6. Decorators help make our code more readable, maintainable and can be used to implement features such as logging, validation, caching, authorization, and more.
Here's an example of a decorator that logs the arguments passed to a method, along with the timestamp of the method call:
function log(target: any, key: string, descriptor: PropertyDescriptor) {
const originalMethod = descriptor.value;
descriptor.value = function(...args: any[]) {
console.log(`[${new Date().toISOString()}] Calling ${key} with arguments: `, args);
return originalMethod.apply(this, args);
}
return descriptor;
}
class Example {
@log
sayHello(name: string) {
console.log(`Hello, ${name}!`);
}
}
const example = new Example();
example.sayHello("John"); // output: [2023-04-20T00:00:00.000Z] Calling sayHello with arguments: ["John"]
// Hello, John!
In this example, the log function is a decorator that takes three parameters: the target
object, the name
of the method being decorated, and the method descriptor
. The decorator
then replaces the original method with a new function that logs
the method call and its arguments before calling the original method. The decorator is then applied to the sayHello
method of the Example class using the @log
syntax. When the sayHello
method is called, the decorator intercepts the call and logs the method arguments and call time before calling the original method.
3. Mixin
TypeScript allows programmers to use Mixins, which is a way to combine classes or interfaces together to create a new class.
class Animal {
constructor(public name: string) {}
eat() {
console.log(`${this.name} is eating.`);
}
}
class Flyable {
fly() {
console.log(`${this.name} is flying.`);
}
}
class Bird extends mixin(Animal, Flyable) {}
const bird = new Bird('Sparrow');
bird.eat(); // output: Sparrow is eating.
bird.fly(); // output: Sparrow is flying.
In the code above, we define two classes Animal
and Flyable
. We then create a new class Bird
by combining Animal
and Flyable
using the mixin
function from the ts-mixer
library. The resulting Bird class has the properties and methods from both Animal
and Flyable
, and can be instantiated and used like any other class.
4. TypeScript Language Service
TypeScript has a TypeScript Language Service, which is a tool that provides APIs for programmers to create additional utilities for TypeScript in IDEs and code editors.
Source: Internet
@nguyenphatit
Top comments (0)