Concept Flow - Creating type aliases
Start
Write 'type' keyword
Give alias a name
Assign a type to alias
Use alias in code
End
This flow shows how to create a type alias by naming it and assigning a type, then using it in code.
type Age = number; let myAge: Age = 30; console.log(myAge);
| Step | Action | Evaluation | Result |
|---|---|---|---|
| 1 | Declare type alias 'Age' as number | type Age = number | Alias 'Age' now means 'number' |
| 2 | Declare variable 'myAge' with type 'Age' | let myAge: Age = 30 | myAge is number 30 |
| 3 | Print 'myAge' | console.log(myAge) | Output: 30 |
| 4 | End of code | No more statements | Execution stops |
| Variable | Start | After Step 2 | Final |
|---|---|---|---|
| myAge | undefined | 30 | 30 |
Creating type aliases in TypeScript: - Use 'type AliasName = Type;' syntax - Alias can be primitive, union, or object types - Use alias as a type annotation - Alias is just a new name, not a new type - Helps make code clearer and reusable
Age for the type number?type, followed by the alias name, an equals sign, and the type.type ID = string | number;
function printId(id: ID) {
console.log(typeof id);
}
printId(123);
printId('abc');ID allows string or number. The function prints the type of the argument.printId(123) prints 'number'. Calling printId('abc') prints 'string'.type User = {
name: string;
age: number;
}
const user: User = {
name: 'Alice',
age: '25'
};User expects age to be a number.userage: '25', which is a string, causing a type error.type Point = { x: number; y: number };
type Circle = { center: Point; radius: number };
type Shape = Circle | Point;Shape object?Point is an object with x and y as numbers. Circle has a center of type Point and a radius number. Shape can be either.Circle exactly. { x: 0, y: 0, radius: 5 } has extra radius on a Point shape, invalid. { center: { x: 0 }, radius: 5 } has incomplete center. { x: '0', y: 0 } has x as string, invalid.Pass the test and this pattern moves unknown