Chuck's Academy

Basic TypeScript

Advanced Typing in TypeScript

TypeScript provides a wide range of advanced tools for working with types. Among them, we find conditional types, mapped types, and other mechanisms that allow for more flexible and safer code. In this chapter, we'll explore how to use these advanced typing features.

Union and Intersection Types

This image shows an illustration of differences between union and intersectionThis image shows an illustration of differences between union and intersection

Union Types

Union types allow a variable to have more than one type. This is useful when a variable can take different forms or values.

typescript
"In this example, the variable id can be either a number or a string. Initially, it is a number, and then it becomes a string."

Intersection Types

Intersection types combine multiple types into one. An object using an intersection type must have all the properties of the combined types.

typescript
"Here, we create a type called Worker that is an intersection of Person and Employee. The variable worker must have both a name property and an employeeId property."

Conditional Types

Conditional types allow creating types that depend on a condition. The basic syntax of a conditional type is T extends U ? X : Y.

Conditional Types Example

typescript
"This example shows a conditional type called IsNumber. If T extends number, the resulting type is 'Yes', otherwise it is 'No'."

Mapped Types

Mapped types allow transforming an existing type into another, applying changes to each of its properties. This is useful for creating modified versions of complex types.

Mapped Type Example

typescript
"In this example, we create a mapped type called Optional that makes all the properties of a given type optional. We apply this to the User interface, creating a new version called OptionalUser where all properties are optional."

Indexed Types

Indexed types allow accessing the types of an object's properties. This is useful when you want to reuse a type in different places.

Indexed Type Example

typescript
"Here we access the type of the id property in the User interface using the indexed type User['id']. This gives us the number type."

Conclusion

In this chapter, we have explored some of the advanced typing features in TypeScript, including union and intersection types, conditional, mapped, and indexed types. These tools enable writing more sophisticated and secure code, especially in large and complex projects.


Ask me anything