Learn TypeScript

Quiz

Quiz

This quiz will test what you have learned about creating types in TypeScript.

1.

We have declared a point variable as follows:

const point = { x: 32, y: 77 };

Will the following assignments generate any type errors?

point.x = 40;
point.y = 80;
point.z = 10;
2.

We have declared a person variable as an object with firstName and level properties as follows:

let person: { firstName: string, level: "high" | "Medium" | "low" };

We want to use this type in several places in our codebase. What's the best way to do this?

type Person = {
firstName: string,
level: "high" | "Medium" | "low"
};
{ firstName: string, level: "high" | "Medium" | "low" };
interface Person {
firstName: string;
level: string;
};
3.

We need to create a type to represent information about a person containing their first name, surname, and an optional age. What types could we use to represent this structure?

type Person = {
firstName: string;
surname: string;
age: number;
}
interface Person {
firstName: string;
surname: string;
age: number;
}
type Person = {
firstName: string;
surname: string;
age?: number;
}
interface Person {
firstName: string;
surname: string;
age?: number;
}
4.

We need to create a type to represent a numeric level that can hold values between 1 and 5. What type can we use to best represent this?

type Level = number;
interface Level = 1 | 2 | 3 | 4 | 5;
type Level = 1 | 2 | 3 | 4 | 5;
5.

Will a type error occur on any of the level assignments below:

enum Status {
Open,
InProgress,
Complete
}
let level: Status;
level = 4;
level = "4";
6.

We have the following type:

type Product = {
name: string;
bestBeforeDate: Date;
}

A bestBeforeDate doesn't apply to every product though. So, we want to allow this to be null or a date. What type best represents this?

type Product = {
name: string;
bestBeforeDate: Date | null;
}
type Product = {
name: string;
bestBeforeDate?: Date;
}
7.

Are the Dog and Apple types structurally equivalent?

type Animal = {
name: string;
}
type Dog = Animal & { size: "small" | "large" }
interface Fruit {
name: string;
}
interface Apple extends Fruit {
size: "small" | "large"
}

Prev

Understanding type compatibility

Next

Introduction

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