Learn TypeScript

Quiz

Quiz

This quiz will test what you have learned about querying types and mapped types.

1.

Consider the code below:

type SavingAction = {
type: "saving";
payload: string[];
}
const savingAction: SavingAction = {
type: "saving",
payload: ["Apple", "Banana", "Strawberry"]
}
type SavedAction = {
type: "saved";
}
const savedAction: SavedAction = {
type: "saved"
}
type Actions = SavingAction | SavedAction;

How can we remove the type annotations from the savingAction and savedAction variables but maintain strong typing.

const savingAction = {
type: "saving",
payload: ["Apple", "Banana", "Strawberry"]
}
const savedAction = {
type: "saved"
}
type Actions = any;
const savingAction = {
type: "saving",
payload: ["Apple", "Banana", "Strawberry"]
}
const savedAction = {
type: "saved"
}
type Actions = savingAction | savedAction;
const savingAction = {
type: "saving",
payload: ["Apple", "Banana", "Strawberry"]
}
const savedAction = {
type: "saved"
}
type Actions = typeof savingAction | typeof savedAction;
2.

What type is structurally the same as PersonKeys below?

type Person = {
firstName: string;
surname: string;
greet: () => void;
}
type PersonKeys = keyof Person;
3.

Structurally, which type is equivalent to the type below?

type Votes = {
[K in "apple" | "banana" | "strawberry"]: number
}
{
apple: number;
banana: number;
strawberry: number;
}
["apple", "banana", "strawberry"];
string[]
4.

Consider the type below:

type Person = {
readonly name: string;
readonly age: number;
}

What would be a generic mapped type that removes all the readonly modifiers from an object type like above?

type Writable<T> = {
[P in keyof T]-?: T[P];
}
type Writable<T> = {
-readonly [P in keyof T]: T[P];
}
type Writable<T> = {
[P in keyof T]-readonly: T[P];
}

Prev

Using `typeof` to infer a type

Next

Introduction

© 2024 Carl Rippon
Privacy Policy
This site uses cookies. Click here to find out more