In JavaScript, variables can hold values of any type at any time. TypeScript, on the other hand, allows you to specify the type of a variable. This helps catch type - related errors at compile - time rather than at runtime.
// Example of static typing
let message: string = "Hello, TypeScript!";
// The following line will cause a compilation error because we are trying to assign a number to a string variable
// message = 123;
Interfaces in TypeScript are used to define the shape of an object. They act as a contract that an object must adhere to.
interface Person {
name: string;
age: number;
address?: string; // Optional property
}
let person: Person = {
name: "John",
age: 30
};
TypeScript supports object - oriented programming concepts like classes. A class is a blueprint for creating objects.
class Animal {
name: string;
constructor(name: string) {
this.name = name;
}
speak() {
console.log(`${this.name} makes a sound.`);
}
}
let dog = new Animal("Dog");
dog.speak();
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 start using TypeScript, you first need to install it globally using npm (Node Package Manager).
npm install -g typescript
TypeScript code needs to be compiled into JavaScript code before it can be run in a browser or a Node.js environment. You can use the tsc
command to compile TypeScript files.
# Create a TypeScript file named app.ts
echo "let message: string = 'Hello, TypeScript!'; console.log(message);" > app.ts
# Compile the TypeScript file
tsc app.ts
To use TypeScript with Node.js, you can use ts-node
which allows you to run TypeScript files directly without having to compile them first.
npm install -g ts-node
// app.ts
let message: string = "Hello from Node.js with TypeScript!";
console.log(message);
ts-node app.ts
To use TypeScript with React, you can create a new React project with TypeScript support using create - react - app
.
npx create-react-app my - app --template typescript
TypeScript can often infer the type of a variable based on its initial value. This reduces the need to explicitly specify types in many cases.
let numberValue = 10; // TypeScript infers the type as number
Optional chaining (?.
) allows you to safely access nested properties without worrying about null or undefined values. Nullish coalescing (??
) provides a default value when a variable is null
or undefined
.
let user = {
address: {
street: "123 Main St"
}
};
let streetName = user?.address?.street;
let optionalValue = null;
let defaultValue = optionalValue?? "Default";
Type assertion is used when you know the type of a value better than TypeScript does. It allows you to override the type inference.
let someValue: any = "this is a string";
let strLength: number = (someValue as string).length;
Interfaces are a great way to define the shape of an object. They make the code more modular and easier to understand. When multiple parts of the code need to work with the same object structure, using an interface ensures consistency.
Avoid creating overly complex types. Simple types are easier to understand and maintain. If a type becomes too complex, break it down into smaller, more manageable types.
Just like in JavaScript, unit testing is crucial in TypeScript. Tools like Jest can be used to write and run unit tests for TypeScript code. This helps catch bugs early and ensures the reliability of the code.
TypeScript offers a wide range of features that make JavaScript development more robust, maintainable, and scalable. By understanding the fundamental concepts, usage methods, common practices, and best practices, developers can take full advantage of TypeScript in their projects. Whether you are working on a small web application or a large - scale enterprise project, TypeScript can help you write better code and catch errors early in the development process.