Understanding TypeScript Types
In the previous article, we introduced TypeScript and its advantages over JavaScript. In this article, we will dive deeper into the language and explore TypeScript's powerful type system. We will discuss basic types, type inference, type annotations, and type aliases.
Basic TypeScript Types
TypeScript supports several basic types that you can use to declare the types of your variables and function parameters. Some common types include:
- number: Represents all numeric values, including integers and floating-point numbers.
- string: Represents a sequence of characters.
- boolean: Represents a true or false value.
- any: Represents any type, allowing you to bypass type checking. Use with caution.
- unknown: Represents an unknown type. Use this type when you do not know the type of a value, and TypeScript will require you to perform a type check before using the value.
Type Inference
TypeScript uses type inference to automatically assign types to your variables and function return values based on their initial values or context. For example:
const message = "Hello, TypeScript!"; // TypeScript infers the type 'string'
const numbers = [1, 2, 3]; // TypeScript infers the type 'number[]'
TypeScript will also infer the return type of a function based on its implementation:
function add(x: number, y: number) {
return x + y; // TypeScript infers the return type 'number'
}
Type Annotations
Although TypeScript is good at inferring types, there are situations where you need to explicitly specify the type of a variable or function parameter. You can do this using type annotations. Type annotations are added after the variable or parameter name, separated by a colon (:
).
Here's an example of using type annotations:
let username: string = "John Doe";
let age: number = 30;
function greet(user: string, userAge: number): string {
return `Hello, ${user}! You are ${userAge} years old.`;
}
Type Aliases
TypeScript allows you to create custom types by defining type aliases. Type aliases are created using the type
keyword and can be used to create more descriptive and reusable types.
Here's an example of using type aliases:
type Point = {
x: number;
y: number;
};
function getDistance(pointA: Point, pointB: Point): number {
const dx = pointA.x - pointB.x;
const dy = pointA.y - pointB.y;
return Math.sqrt(dx * dx + dy * dy);
}
const p1: Point = { x: 0, y: 0 };
const p2: Point = { x: 3,y: 4 };
console.log(getDistance(p1, p2)); // Output: 5
Union Types and Intersection Types
TypeScript supports more advanced type constructs such as union types and intersection types. Union types allow a value to be one of several types, while intersection types combine multiple types into a single type.
Here's an example of using union types:
type StringOrNumber = string | number;
function stringify(value: StringOrNumber): string {
return value.toString();
}
console.log(stringify(42)); // Output: '42'
console.log(stringify('Hello')); // Output: 'Hello'
And here's an example of using intersection types:
type Named = {
name: string;
};
type Aged = {
age: number;
};
type Person = Named & Aged;
function printPerson(person: Person): void {
console.log(`${person.name} is ${person.age} years old.`);
}
const john: Person = { name: 'John Doe', age: 30 };
printPerson(john); // Output: 'John Doe is 30 years old.'
Conclusion
In this article, we discussed TypeScript's powerful type system, including basic types, type inference, type annotations, type aliases, union types, and intersection types. Understanding these concepts is crucial for writing effective TypeScript code. In the next article, we will explore how to work with TypeScript interfaces.
Table of Contents: Typescript for Beginners
- An Introduction to TypeScript: JavaScript's Powerful Superset
- Understanding TypeScript Types
- Working with TypeScript Interfaces
- Mastering TypeScript Classes and Inheritance
- TypeScript Generics: Flexible and Type-Safe Code
- Organizing Code with TypeScript Modules
- Advanced TypeScript Types and Techniques
- Using TypeScript Decorators to Enhance Your Code
- Configuring the TypeScript Compiler for Your Project
- TypeScript Best Practices for Cleaner and More Maintainable Code