TypeScript is a powerful superset of JavaScript that allows developers to add static types to their code, which greatly enhances code readability and maintainability. While many developers are familiar with basic types like string
, number
, and boolean
, TypeScript also offers a variety of advanced types that can significantly improve your coding experience. Let’s take a closer look at these advanced types and how you can use them effectively in your projects.
Union types allow you to define a variable that can hold values of multiple types. This is particularly useful when a function can accept different types of inputs.
function printId(id: number | string) { console.log(`Your ID is: ${id}`); } printId(101); // Output: Your ID is: 101 printId('202'); // Output: Your ID is: 202
In this example, the printId
function can accept both a number
and a string
as its argument, providing flexibility in how the function can be called.
Intersection types allow you to combine multiple types into one. This is useful when you want to create a new type that includes properties from multiple existing types.
interface Person { name: string; } interface Employee { id: number; } type EmployeePerson = Person & Employee; const employee: EmployeePerson = { name: "Jane Doe", id: 123, }; console.log(employee); // Output: { name: "Jane Doe", id: 123 }
Here, the EmployeePerson
type combines the Person
and Employee
types, letting us create an object that satisfies both interfaces.
Type guards are special constructs that help you narrow down types within a conditional block. This allows TypeScript to understand what specific type a variable holds, enabling better type checking.
function processValue(value: number | string) { if (typeof value === "string") { console.log(`String value: ${value.toUpperCase()}`); } else { console.log(`Numeric value: ${value.toFixed(2)}`); } } processValue(10); // Output: Numeric value: 10.00 processValue("hello"); // Output: String value: HELLO
The processValue
function uses the typeof
operator as a type guard to differentiate between string
and number
types, ensuring appropriate operations are performed based on the type of value
.
Conditional types enable you to create types that depend on a condition. This is similar to a ternary operator for types and can be incredibly powerful for advanced type manipulation.
type IsString<T> = T extends string ? "This is a string" : "This is not a string"; type Check1 = IsString<string>; // Check1 is "This is a string" type Check2 = IsString<number>; // Check2 is "This is not a string"
In this example, the type IsString
evaluates whether the type T
is a string
or not, allowing the creation of types based on conditions.
Mapped types let you create new types by transforming properties of an existing type. This is useful for creating variations of existing types without duplicating code.
type User = { name: string; age: number; }; type ReadonlyUser = { readonly [K in keyof User]: User[K]; }; const user: ReadonlyUser = { name: "Alice", age: 30, }; // user.name = "Bob"; // Error: Cannot assign to 'name' because it is a read-only property
Here, ReadonlyUser
is a new type that makes all properties of the original User
type read-only.
Template literal types are a recent addition to TypeScript that allows you to create types using string literals. This feature is great for creating structured string-based types.
type EventType = "click" | "hover" | "submit"; type EventListener<K extends EventType> = `${K}Listener`; let clickListener: EventListener<"click"> = "clickListener"; // Valid let hoverListener: EventListener<"hover"> = "hoverListener"; // Valid // let invalidListener: EventListener<"click"> = "blurListener"; // Error: Type '"blurListener"' is not assignable
In this example, EventListener
generates a new type based on the provided event type, demonstrating how you can use template literals for type generation.
By leveraging these advanced types, you can take full advantage of TypeScript's capabilities, creating more dynamic and type-safe code. Whether you are building a large-scale application or maintaining a small project, understanding these advanced types is key to writing code that is both efficient and easy to maintain. Explore these types further, experiment, and watch as TypeScript elevates your programming experience!
17/10/2024 | TypeScript
03/12/2024 | TypeScript
17/10/2024 | TypeScript
17/10/2024 | TypeScript
17/10/2024 | TypeScript
17/10/2024 | TypeScript
17/10/2024 | TypeScript
17/10/2024 | TypeScript