Quiz about Unions, Intersections & Aliases - TypeScript Quiz
TypeScript is a superset of JavaScript that adds static typing to the language. One of the powerful features of TypeScript is its ability to work with complex types, including unions, intersections, and type aliases. These concepts can be a bit tricky to grasp, especially for those new to TypeScript. This blog will not only explain these concepts but also provide a quiz to test your understanding.
Intersection types combine multiple types into one. An intersection type requires a value to satisfy all the types in the intersection. You use the ampersand symbol & to define an intersection.
Intersections are useful when you want to create a type that has all the properties of multiple types. For example, if you have different mixins in your application, you can use intersections to combine them.
Aliases are often used for complex types or when you want to reuse a type in multiple places. For example, if you have a specific shape of an object that is used in multiple functions, you can create an alias for it.
type User = { name: string; age: number; email: string;};function printUser(user: User) { console.log(user.name, user.age, user.email);}
What is the correct way to define a union type for a variable that can be a string or a boolean?
A. let value: string & boolean;
B. let value: string | boolean;
C. let value: [string, boolean];
Type Narrowing: When working with union types, it's often necessary to perform type narrowing to access the specific properties or methods of each type. You can use type guards like typeof or instanceof for this purpose.
function printValue(value: string | number) { if (typeof value === "string") { console.log(value.toUpperCase()); } else { console.log(value.toFixed(2)); }}
Avoid Over - Complexity: Intersection types can become very complex if you combine too many types. Try to keep them simple and only use intersections when necessary.
Unions, intersections, and aliases are powerful features in TypeScript that allow you to work with complex types effectively. By understanding these concepts and practicing with the quiz provided, you can improve your TypeScript skills and write more robust code.