One of the core features of TypeScript is static typing. In JavaScript, variables can hold values of any type, which can lead to hard - to - debug errors. TypeScript allows you to define the type of a variable, function parameter, or return value.
// Defining a variable with a specific type
let message: string = "Hello, TypeScript!";
Interfaces in TypeScript are used to define the shape of an object. They can describe the properties and their types, as well as the methods an object should have.
interface Person {
name: string;
age: number;
greet(): void;
}
let person: Person = {
name: "John",
age: 30,
greet() {
console.log(`Hello, my name is ${this.name} and I'm ${this.age} years old.`);
}
};
TypeScript supports object - oriented programming concepts like classes. A class is a blueprint for creating objects.
class Animal {
constructor(public name: string) {}
move(distance: number = 0) {
console.log(`${this.name} moved ${distance}m.`);
}
}
let cat = new Animal("Cat");
cat.move(10);
Enums are a way to define a set of named constants. They make the code more readable and maintainable.
enum Color {
Red,
Green,
Blue
}
let myColor: Color = Color.Green;
console.log(myColor);
To use TypeScript, you first need to install it globally using npm.
npm install -g typescript
TypeScript code needs to be compiled to JavaScript. You can use the tsc
command to compile a TypeScript file.
tsc myfile.ts
To use TypeScript in a Node.js project, you can follow these steps:
npm init -y
npm install typescript --save -dev
tsconfig.json
file: npx tsc --init
.ts
file, for example, index.ts
npx tsc
node index.js
Create a new React project with TypeScript support using Create React App:
npx create - react - app my - app --template typescript
Type annotations are used to explicitly define the type of a variable, function parameter, or return value. They are useful when the type cannot be inferred by TypeScript.
function add(a: number, b: number): number {
return a + b;
}
TypeScript can often infer the type of a variable based on its initial value. This reduces the need for explicit type annotations.
let num = 10; // TypeScript infers the type as number
Arrays in TypeScript can have a specific type for their elements. Tuples are arrays with a fixed number of elements, where each element can have a different type.
// Array of numbers
let numbers: number[] = [1, 2, 3];
// Tuple
let personTuple: [string, number] = ["John", 30];
Interfaces should be as simple as possible. Avoid creating overly complex interfaces with too many properties or methods. This makes the code more maintainable and easier to understand.
Union types allow a variable to have one of several types, while intersection types combine multiple types into one. Use them sparingly and only when necessary to avoid code complexity.
// Union type
let value: string | number;
value = "Hello";
value = 10;
// Intersection type
interface A {
a: string;
}
interface B {
b: number;
}
let obj: A & B = { a: "test", b: 10 };
Type guards are expressions that perform a runtime check that guarantees the type in a certain scope. They are useful when working with union types.
function printValue(value: string | number) {
if (typeof value === "string") {
console.log(value.toUpperCase());
} else {
console.log(value.toFixed(2));
}
}
TypeScript is a powerful language that brings many benefits to JavaScript development, such as improved code quality, better tooling support, and easier refactoring. By understanding its fundamental concepts, usage methods, common practices, and best practices, developers can write more robust and maintainable code. Whether you are working on a small Node.js project or a large - scale React application, TypeScript can be a valuable addition to your toolkit.