Typescript type alias
Created By: chatGPT
In TypeScript, a type alias is a way to define a new name for a type. You can use type aliases to create a clear and descriptive name for complex types, making your code easier to understand and maintain. Type aliases can represent any valid TypeScript type, such as primitive types, union types, or intersection types.
type Point = {
x: number;
y: number;
};
const point: Point = {
x: 10,
y: 20,
};
You can also use union types in type aliases, which allows a variable to be one of several types. This is particularly useful when your function can accept multiple types of input.
type StringOrNumber = string | number;
function logValue(value: StringOrNumber) {
console.log(value);
}
logValue('Hello');
logValue(42);
Type aliases can also help when dealing with tuples and more complex constructs. You can define a type alias for a tuple instead of repeatedly writing out the type, leading to more readable and maintainable code.
type StringNumberTuple = [string, number];
const example: StringNumberTuple = ['Hello', 100];
Using type aliases is a great way to improve your TypeScript development process, especially in large applications. They ensure that your types are consistent throughout the codebase and provide clear documentation right within your code.
type User = {
id: number;
name: string;
isAdmin: boolean;
};
const user: User = {
id: 1,
name: 'John Doe',
isAdmin: true,
};