TypeScript allows you to add type annotations to variables, functions, and parameters. This helps in making the code more explicit about the data types it can handle.
// Variable with type annotation
let message: string = "Hello, TypeScript!";
// Function with parameter and return type annotations
function add(a: number, b: number): number {
return a + b;
}
Interfaces in TypeScript are used to define the structure of an object. They can describe the shape of an object, including the names and types of its properties.
interface Person {
name: string;
age: number;
greet(): void;
}
const person: Person = {
name: "Alice",
age: 25,
greet() {
console.log(`Hello, my name is ${this.name} and I'm ${this.age} years old.`);
}
};
Classes in TypeScript are similar to classes in other object - oriented programming languages. They can have properties, methods, and constructors.
class Animal {
name: string;
constructor(name: string) {
this.name = name;
}
move(distance: number = 0) {
console.log(`${this.name} moved ${distance}m.`);
}
}
const dog = new Animal("Buddy");
dog.move(10);
Enums are used to define a set of named constants. They can make the code more readable and self - documenting.
enum Color {
Red,
Green,
Blue
}
let myColor: Color = Color.Green;
console.log(myColor); // Output: 1
To start using TypeScript, you first need to install it globally using npm (Node Package Manager).
npm install -g typescript
Create a tsconfig.json
file in your project root directory to configure the TypeScript compiler. A basic tsconfig.json
might look like this:
{
"compilerOptions": {
"target": "ES6",
"module": "commonjs",
"strict": true
}
}
TypeScript supports a variety of basic types such as number
, string
, boolean
, null
, undefined
, and any
.
let num: number = 10;
let str: string = "hello";
let isDone: boolean = false;
let maybeNull: null = null;
let maybeUndefined: undefined = undefined;
let notSure: any = 4;
notSure = "a string";
Functions in TypeScript can have type annotations for parameters and return values.
function multiply(a: number, b: number): number {
return a * b;
}
const result = multiply(5, 3);
TypeScript can often infer the types of variables based on their initial values, reducing the need for explicit type annotations.
let inferredNumber = 10; // TypeScript infers the type as number
Generics in TypeScript allow you to create reusable components that can work with different types.
function identity<T>(arg: T): T {
return arg;
}
let output1 = identity<string>("myString");
let output2 = identity<number>(100);
Type guards are used to narrow down the type of a variable within a conditional block.
function printValue(value: string | number) {
if (typeof value === "string") {
console.log(value.toUpperCase());
} else {
console.log(value.toFixed(2));
}
}
Enabling strict mode in tsconfig.json
forces TypeScript to perform more comprehensive type checks, helping to catch potential errors early.
{
"compilerOptions": {
"strict": true
}
}
The any
type in TypeScript bypasses type checking. It should be used sparingly, as it can lead to hard - to - debug errors. Try to be as specific as possible with type definitions.
When defining interfaces, keep them simple and focused. Avoid over - complicating the structure. For example, instead of creating a large, monolithic interface, break it into smaller, more manageable interfaces.
// Instead of this
interface ComplexPerson {
name: string;
age: number;
address: {
street: string;
city: string;
zip: string;
};
hobbies: string[];
}
// Do this
interface Address {
street: string;
city: string;
zip: string;
}
interface Person {
name: string;
age: number;
address: Address;
hobbies: string[];
}
TypeScript is a powerful and versatile language that offers significant benefits in terms of code maintainability, error - catching, and developer productivity. By understanding its fundamental concepts, usage methods, and following common and best practices, developers can write more reliable and scalable JavaScript applications. Whether you are working on small projects or large - scale enterprise applications, TypeScript can enhance the quality of your codebase.