TypeScript

0.0(0)
studied byStudied by 2 people
learnLearn
examPractice Test
spaced repetitionSpaced Repetition
heart puzzleMatch
flashcardsFlashcards
Card Sorting

1/4

encourage image

There's no tags or description

Looks like no tags are added yet.

Study Analytics
Name
Mastery
Learn
Test
Matching
Spaced

No study sessions yet.

5 Terms

1
New cards

Type defintion (User with name and age)

type User = {
name: string,
age: number
}
2
New cards

Interface definition (Admin with name and role)

interface Admin {
name: string;
age: number;
}
3
New cards

Union of two types/interfaces (Person from Admin and User)

type Person = Admin | User

4
New cards

Checking if it is a certain type? Come back to this

A few options:

  1. Check for a unique property

    1. example:

      if ('role' in Person)
  2. Use instanceOf - this only works with classes

    1. example:

      const userAccount = login(); 
      if (userAccount instanceof FreeAccount) {
        console.log('Welcome to the free account!');
  3. Use typeof

    1. example:

5
New cards

Using type predicates

To define a user-defined type guard, we simply need to define a function whose return type is a type predicate

function isFish(pet: Fish | Bird): pet is Fish {
  return (pet as Fish).swim !== undefined;
}

pet is Fish is the type predicate.