Menu
Coddy logo textTech

Type Aliases for Primitives

Part of the Introduction To TypeScript section of Coddy's JavaScript journey — lesson 30 of 73.

TypeScript's type keyword allows you to create a type alias - essentially a custom name for any existing type, including primitive types and their combinations.

The syntax is straightforward: you use the type keyword followed by your chosen name, an equals sign, and the type you want to alias:

type UserID = string | number;
type Score = number;
type IsActive = boolean;

Once you've created a type alias, you can use it anywhere you would use the original type. This is particularly valuable when working with union types, as it makes your code more readable and self-documenting:

type UserID = string | number;

let currentUser: UserID = "user123";
let adminUser: UserID = 42;

Type aliases don't create new types - they simply provide alternative names for existing ones. This means UserID and string | number are completely interchangeable, but using the alias makes your code's intent much clearer to other developers.

challenge icon

Challenge

Easy

Create a type alias named UserID for a union type that can be either a string or a number.

Create a type alias named Priority for a union type that can be either a string or a boolean.

Create a type alias named Status for the string type.

Now declare the following variables using your type aliases:

  • Declare a variable named currentUser of type UserID and assign it the string value "admin123"
  • Declare a variable named guestUser of type UserID and assign it the number value 42
  • Declare a variable named taskPriority of type Priority and assign it the string value "high"
  • Declare a variable named isUrgent of type Priority and assign it the boolean value true
  • Declare a variable named orderStatus of type Status and assign it the string value "pending"

Print each variable's value on a separate line in the order they were declared above.

Try it yourself

// TODO: Write your code here
// Create type aliases for UserID, Priority, and Status
// Then declare the variables and assign the specified values

// Print each variable's value
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Introduction To TypeScript