type keyword in typescript
- User
type keyword in typescript
- Assistant
In TypeScript, the
typekeyword is used to define a type alias. A type alias gives a name to any type annotation so that you can refer to it later on without having to repeat the entire type annotation. This is particularly useful for complex types or union types that you want to reuse throughout your code.Here's how you can use the
typekeyword in TypeScript:type StringOrNumber = string | number; // Now you can use the type alias in function parameters, variables, return types etc. function logMessage(message: StringOrNumber): void { if (typeof message === 'string') { console.log("String message:", message); } else { console.log("Number message:", message); } } let value: StringOrNumber; value = "Hello TypeScript"; logMessage(value); value = 101; logMessage(value);In this example, the type
StringOrNumberis a union type that can be either astringor anumber. Throughout the code, you can now useStringOrNumberas a type instead of writingstring | numberevery time.It's important to note that type aliases in TypeScript are not limited to union types; they can be used to alias any valid TypeScript type, including primitives, interfaces, tuples, and more:
// Primitive type type AliasForString = string; // Interface interface User { id: number; name: string; } type UserAlias = User; // Tuple type StringNumberPair = [string, number]; // And so on...Type aliases can also be generic, allowing you to create more flexible and reusable types:
type Container<T> = { value: T }; let stringContainer: Container<string> = { value: "Hello World" }; let numberContainer: Container<number> = { value: 42 };In the above example,
Containeris a generic type that takes a type parameterT. You can instantiateContainerwith any type you choose, creating aContainerof strings, numbers, or any other type.
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.