Learn TypeScript

Quiz

Quiz

This quiz will test what you have learned about immutable types.

1.

Consider the following code:

type Readings = {
readonly date: Date;
readonly values: number[];
}
const readings: Readings = {
date: new Date(),
values: [4, 3, 5]
}
readings.values.push(1);

Does a type error occur on the assignment on the last line?

2.

Consider the following code:

type Person = {
firstName: string;
surname: string;
profile: {
rating: string;
}
}
const bob: Readonly<Person> = {
firstName: "Bob",
surname: "Keel",
profile: {
rating: "medium"
}
bob.surname = "Steel";
bob.profile.rating = "high";
};

Do any type errors occur on the surname and rating assignments on the last 2 lines?

3.

Consider the following code:

type Person = {
firstName: string;
surname: string;
}
const bob: Readonly<Person> = {
firstName: "Bob",
surname: "Keel"
};
bob.surname = "Smith";
console.log(bob.surname);

What will be output to the console when the transpiled JavaScript is executed?

4.

Consider the following code:

const bob = {
name: {
firstName: "Bob",
surname: "Keel"
},
profile: {
rating: "medium"
}
} as const;
bob.name.surname = "Smith";
bob.profile.rating = "high";

Do any type errors occur on the assignments on the last 2 lines?

5.

Consider the following code:

type Person = {
name: string;
profile: {
level: number;
}
};
function increaseLevel(person: Readonly<Person>) {
person.profile.level++;
return person;
}

Do any type errors occur in the function?

6.

Consider the following code:

type Person = {
firstName: string;
surname: string;
}
const bob: Readonly<Person> = Object.freeze({
firstName: "Bob",
surname: "Keel"
});
bob.surname = "Smith";
console.log(bob.surname);

What will be output to the console when the transpiled JavaScript is executed?

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