1/4
Looks like no tags are added yet.
Name | Mastery | Learn | Test | Matching | Spaced |
---|
No study sessions yet.
Type defintion (User with name and age)
type User = {
name: string,
age: number
}
Interface definition (Admin with name and role)
interface Admin {
name: string;
age: number;
}
Union of two types/interfaces (Person from Admin and User)
type Person = Admin | User
Checking if it is a certain type? Come back to this
A few options:
Check for a unique property
example:
if ('role' in Person)
Use instanceOf - this only works with classes
example:
const userAccount = login();
if (userAccount instanceof FreeAccount) {
console.log('Welcome to the free account!');
Use typeof
example:
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.