Conditional Types
Enabling conditional types helps you form types in line with a certain test, this is practical in terms of making types that rely on other types.
Example: In the given below example we are using Conditional Type with Interfaces.
interface Animal {
live(): void;
}
interface Dog extends Animal {
bark(): void;
}
type Example1 = Dog extends Animal ?
number : string; // number
type Example2 = RegExp extends Animal ?
number : string; // string
const example1Value: Example1 = 42;
const example2Value: Example2 = "Not an animal";
console.log(example1Value); // 42
console.log(example2Value); // "Not an animal"
Output:
42
Not an animal
Type Manipulation in TypeScript
TypeScript offers strong tools for types manipulation and transformation, these tools allow programmers to create new types by composing, intersecting, unionizing, mapping and conditioning existing ones, in this article we will investigate some of the advanced type-manipulation features in TypeScript including:
Table of Content
- Intersection Types (&)
- Union Types (|)
- Mapped Types
- Conditional Types
Contact Us