I'm preparing a advance typescript talk. Explain type literal combinations in typescript
- User
I'm preparing a advance typescript talk. Explain type literal combinations in typescript
- Assistant
Type literal combinations in TypeScript refer to the ability to combine multiple type literals to create a new type. This is a powerful feature that allows you to create complex types with precise shapes.
Here are some ways to combine type literals in TypeScript:
- Union Types: Union types allow you to create a type that can be one of several different types. You can create a union type by using the pipe (|) symbol to separate the types. For example:
typescripttype StringOrNumber = string | number;In this example, the
StringOrNumbertype can be either astringor anumber.- Intersection Types: Intersection types allow you to create a type that has all the properties of two or more types. You can create an intersection type by using the ampersand (&) symbol to combine the types. For example:
typescripttype Name = { first: string; last: string; }; type ContactInfo = { email: string; phone: string; }; type Person = Name & ContactInfo;In this example, the
Persontype has all the properties of both theNameandContactInfotypes.- Type Guards: Type guards allow you to narrow down the type of a variable within a conditional block. You can use the
typeoforinstanceofoperators to create a type guard. For example:
typescriptfunction printValue(value: string | number) { if (typeof value === "string") { console.log(value.toUpperCase()); } else { console.log(value.toFixed(2)); } }In this example, the
printValuefunction takes a parameter of typestring | number. Within the function, we use a type guard to check if thevalueis astringor anumber, and then call the appropriate method based on the type.- Type Aliases: Type aliases allow you to create a new name for an existing type. You can use the
typekeyword to create a type alias. For example:
typescripttype UserId = number;
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.