Sure, I'd be happy to help you prepare for your advanced TypeScript talk! Type literal combinations in TypeScript refer to the ability to create complex types by combining various type literals, such as string literals, numeric literals, and boolean literals, along with other type constructs like interfaces, unions, and intersections. Here are some examples to illustrate this concept:
String Literal Types: You can define a type that only accepts specific string values using string literal types. For instance:
typescript
type Color = 'red' | 'green' | 'blue';
let myColor: Color = 'red'; // OK
myColor = 'yellow'; // Error: Type '"yellow"' is not assignable to type 'Color'
Numeric Literal Types: Similar to string literals, you can define types that only accept specific numeric values:
typescript
type HTTPStatus = 200 | 404 | 500;
let statusCode: HTTPStatus = 200; // OK
statusCode = 301; // Error: Type '301' is not assignable to type 'HTTPStatus'
Boolean Literal Types: You can also define types that only accept true or false values:
typescript
type Flag = true | false;
let isActive: Flag = true; // OK
isActive = 'yes'; // Error: Type '"yes"' is not assignable to type 'Flag'
Union Types: You can combine different types, including literals, using union types:
typescript
type UserInput = string | number | boolean;
let input: UserInput = 'hello'; // OK
input = 123; // OK
input = true; // OK
input = {}; // Error: Type '{}' is not assignable to type 'UserInput'
Intersection Types: You can create a type that combines the properties of multiple types using intersection types:
typescript
interface Person {
name: string;
}
interface Employee {
id: number;
}
type EmployeePerson = Person & Employee;
let employee: EmployeePerson = { name: 'John', id: 123 }; // OK
employee = { name: 'Jane' }; // Error: Property 'id' is missing in type '{ name: string; }' but required in type 'EmployeePerson'
Type Literal Combinations: You can combine type literals with other type constructs to create more complex types:
typescript
type Action = {
type: 'ADD' | 'REMOVE';
payload: number;
};
let action: Action = { type: 'ADD', payload: 1 }; // OK
action = { type: 'UPDATE', payload: 'hello' }; // Error: Type '"UPDATE"' is not assignable to type '"ADD" | "REMOVE"'
These examples demonstrate how you can use type literal combinations in TypeScript to create more precise and expressive types, leading to better type safety and code maintainability.
User
type permutations in typescript
Assistant
In TypeScript, you can create type permutations using mapped types, conditional types, and template literal types. Here's an example of how to generate permutations of a union type:
Suppose you have a union type Color and you want to create a new type ColorPair that represents all possible pairs of colors:
Here's a breakdown of how the ColorPair type is constructed:
We use a mapped type to iterate over each color in the Color union type.
For each color K, we create another mapped type that iterates over each color P in the Color union type.
For each pair of colors K and P, we create an object type with two properties: first of type K and second of type P.
We then index the resulting object type with the Color union type to get a union of all possible pairs.
You can also create permutations of more complex types using the same approach. For example, here's how to create permutations of a union type with multiple properties:
typescript
type Shape = {
type: 'circle' | 'square';
color: Color;
};
type ShapePair = {
[K in Shape['type']]: {
[P in Shape['type']]: {
first: K;
second: P;
color: Color;
};
}[Shape['type']];
}[Shape['type']];
// The resulting type is equivalent to:
// type ShapePair =
// | { first: 'circle'; second: 'circle'; color: Color; }
// | { first: 'circle'; second: 'square'; color: Color; }
// | { first: 'square'; second: 'circle'; color: Color; }
// | { first: 'square'; second: 'square'; color: Color; }
These examples demonstrate how you can use mapped types, conditional types, and template literal types in TypeScript to create type permutations, leading to more flexible and expressive types.
User
explain each with real world examples
Assistant
Sure, I'd be happy to explain each of the TypeScript features used in the previous examples with real-world examples.
Mapped Types: Mapped types allow you to create new types by transforming the properties of an existing type. For example, you can use mapped types to create a type that represents a read-only version of an existing type:
typescript
type ReadonlyUser = {
readonly [K in keyof User]: User[K];
};
interface User {
name: string;
age: number;
}
let user: User = { name: 'John', age: 30 };
let readonlyUser: ReadonlyUser = user;
// The following line will result in an error because the properties are read-only
readonlyUser.name = 'Jane'; // Error: Cannot assign to 'name' because it is a read-only property
Conditional Types: Conditional types allow you to create types that depend on other types. For example, you can use conditional types to create a type that represents the return type of a function based on its input type:
typescript
type FunctionReturnType<T> = T extends (...args: any[]) => infer R ? R : never;
function add(a: number, b: number): number {
return a + b;
}
type AddReturnType = FunctionReturnType<typeof add>; // number
Template Literal Types: Template literal types allow you to create types that represent string literals with a specific format. For example, you can use template literal types to create a type that represents a valid CSS color string:
typescript
type CSSColor = `#${string}` | `rgb(${number}, ${number}, ${number})` | `rgba(${number}, ${number}, ${number}, ${number})`;
let color: CSSColor = '#ff0000'; // OK
color = 'red'; // Error: Type '"red"' is not assignable to type 'CSSColor'
Type Permutations: As shown in the previous examples, you can use mapped types, conditional types, and template literal types to create type permutations. Here's a real-world example of creating permutations of a union type that represents different types of notifications:
User
explain the second point with complete code examples?
Assistant
Sure, I'd be happy to explain the second point (Conditional Types) with complete code examples.
Conditional types allow you to create types that depend on other types. They are particularly useful when you want to create a type that depends on the properties or structure of another type. Here are some examples to illustrate how conditional types work:
Extracting the return type of a function: You can use conditional types to extract the return type of a function based on its input type:
typescript
type FunctionReturnType<T> = T extends (...args: any[]) => infer R ? R : never;
function add(a: number, b: number): number {
return a + b;
}
type AddReturnType = FunctionReturnType<typeof add>; // number
function greet(name: string): string {
return `Hello, ${name}!`;
}
type GreetReturnType = FunctionReturnType<typeof greet>; // string
Filtering union types: You can use conditional types to filter union types based on a condition:
typescript
type FilterUnion<T, U> = T extends U ? T : never;
type NumberOrString = number | string;
type NumberOnly = FilterUnion<NumberOrString, number>; // number
type StringOnly = FilterUnion<NumberOrString, string>; // string
Excluding types: You can use conditional types to exclude types from a union type:
typescript
type ExcludeType<T, U> = T extends U ? never : T;
type NumberOrString = number | string;
type NotNumber = ExcludeType<NumberOrString, number>; // string
Mapping types based on a condition: You can use conditional types to map types based on a condition:
typescript
type MapType<T, U> = T extends U ? { [K in keyof T]: T[K] } : never;
interface User {
name: string;
age: number;
}
type UserWithId = MapType<User, { id: number }>; // { id: number; name: string; age: number; }
Creating a type that depends on a generic type parameter: You can use conditional types to create a type that depends on a generic type parameter:
These examples demonstrate how you can use conditional types in TypeScript to create more flexible and expressive types that depend on other types. By using conditional types, you can create types that better represent real-world scenarios and improve type safety in your code.
User
const possibleValues = [1,2,3,4,5] as const
type PossibleValues = typeof possibleValues[number]
const anotherPossibleValues = [6,7,8,9,10] as const
type AnotherPossibleValues = typeof anotherPossibleValues[number]
type combined = ${PossibleValues} ${AnotherPossibleValues}
rewrite this code with real world example
Assistant
Sure, I can provide a real-world example that demonstrates the use of the code you provided. Let's consider a scenario where we have two sets of possible values for different types of products in an e-commerce store. We want to create a type that represents the combination of these values as a string. Here's how we can rewrite the code with a real-world example:
typescript
// Define the possible product categories as a readonly tuple
const productCategories = ['electronics', 'clothing', 'books'] as const;
// Define the type for product categories
type ProductCategory = typeof productCategories[number];
// Define the possible product sizes as a readonly tuple
const productSizes = ['small', 'medium', 'large', 'extra-large'] as const;
// Define the type for product sizes
type ProductSize = typeof productSizes[number];
// Define the combined type for product category and size
type ProductCategoryAndSize = `${ProductCategory} ${ProductSize}`;
// Example usage
const product1: ProductCategoryAndSize = 'electronics small';
const product2: ProductCategoryAndSize = 'clothing medium';
const product3: ProductCategoryAndSize = 'books extra-large';
// This will result in an error because 'shoes' is not a valid product category
const invalidProduct: ProductCategoryAndSize = 'shoes small';
In this example, we define two readonly tuples, productCategories and productSizes, that represent the possible values for product categories and sizes, respectively. We then use the typeof operator and the [number] index type query to create the ProductCategory and ProductSize types. Finally, we use template literal types to create the ProductCategoryAndSize type, which represents the combination of a product category and size as a string. This type can be used to ensure type safety when working with product data in the e-commerce store.
User
Use the template string combination
Assistant
Sure, here's an example of how you can use template string combination to create a type that represents a combination of two other types:
typescript
// Define the possible colors as a readonly tuple
const colors = ['red', 'green', 'blue'] as const;
// Define the type for colors
type Color = typeof colors[number];
// Define the possible sizes as a readonly tuple
const sizes = ['small', 'medium', 'large'] as const;
// Define the type for sizes
type Size = typeof sizes[number];
// Define the combined type for color and size
type ColorAndSize = `${Color} ${Size}`;
// Example usage
const item1: ColorAndSize = 'red small';
const item2: ColorAndSize = 'green medium';
const item3: ColorAndSize = 'blue large';
// This will result in an error because 'yellow' is not a valid color
const invalidItem: ColorAndSize = 'yellow small';
In this example, we define two readonly tuples, colors and sizes, that represent the possible values for colors and sizes, respectively. We then use the typeof operator and the [number] index type query to create the Color and Size types. Finally, we use template literal types to create the ColorAndSize type, which represents the combination of a color and size as a string. This type can be used to ensure type safety when working with item data that has both a color and size attribute.
These examples demonstrate how you can use mapped types, conditional types, template literal types, and type permutations in TypeScript to create more flexible and expressive types that better represent real-world scenarios.
typescript
type IsNumber<T> = T extends number ? true : false;
type A = IsNumber<number>; // true
type B = IsNumber<string>; // false