Video

Watch the full video on YouTube:

Basic Types, Pick and Omit

Basic Types in TypeScript

TypeScript offers several primitive types that help us define the nature of our data:

  • string: For text strings
  • number: For numbers (integers and decimals)
  • boolean: For true/false values

Unlike languages like Java or Swift, TypeScript doesn’t distinguish between integers and decimals. Everything is handled with the number type.

let myName: string = "Angel"
let myAge: number = 30
let myJob: string = "developer"
let isMale: boolean = true

Interfaces and Types

TypeScript allows us to define the structure of our objects using interfaces or types.

Interfaces

An interface defines the shape an object must have:

interface User {
  name: string
  age: number
  job: string
  isMale: boolean
}

Types

A type is similar to an interface but with different syntax:

type UserType = {
  name: string
  age: number
  job: string
  isMale: boolean
}

Interfaces vs Types

The main differences are:

  • Interfaces are easier for the compiler to digest
  • Interfaces can be extended with extends
  • Types are composed with the & (ampersand) operator

Extending Interfaces

interface UserWithHobby extends User {
  hobbies: string[]
}

Composing Types

type UserWithHobbyType = UserType & {
  hobbies: string[]
}

Union Types

Union types allow a variable to be of several types:

type MaybeHaveHobbiesUser = UserType | UserWithHobbyType

Utility Types: Pick and Omit

Omit

Omit allows us to create a type by excluding certain attributes:

interface GenderlessUser extends Omit<User, "isMale"> {
  // Doesn't have the isMale attribute
}

Pick

Pick allows us to create a type including only certain attributes:

interface NameAndAgeOnlyUser extends Pick<User, "name" | "age"> {
  // Only has name and age
}

Optional Properties

We can make a property optional using ?:

interface UserWithOptionalHobbies extends User {
  hobbies?: string[]
}

Optional Chaining

When working with optional properties, we can use optional chaining ?. to access them safely:

user.hobbies?.push("gaming")

Conclusion

In this video we learned about TypeScript basic types, how to define interfaces and types, and how to use Pick and Omit utilities to create derived types. These concepts are fundamental for working effectively with TypeScript.

TypeScript Guide 01: Introduction to TypeScriptTypeScript Guide 03: Record, unknown, typeof and keyof