Learn TypeScript

Quiz

Quiz

This quiz will test what you have learned about some of the standard types in TypeScript.

1.

Will TypeScript detect a problem with the following? If so, what's the problem?

const today = new Date();
console.log(today.getWeekDay());
2.

What is the return type in the function below?

function logMessage(message: string) {
return console.log(message);
}
3.

What are correct type annotations for creating an array of dates?

4.

What will TypeScript infer the type of the people variable to be in the declaration below?

let people = ["Paula", "Bob", "Sam"];
5.

We have a function below that takes in a varying number of message parameters and outputs them to the console. How can we strongly-type the messages rest parameter so that only string types can be passed?

function outputMessages(...messages) {
messages.forEach(message => console.log(message));
}
6.

Consider the function below that calls a function in a 3rd party library that returns the result a calculation. The code isn't strongly-typed because thirdPartyCalculation returns a value of type any. Is it possible to use the unknown type to make the code more strongly-typed?

function doWork() {
const result = thirdPartyCalculation();
return result + 1;
}
function doWork() {
const result: unknown = thirdPartyCalculation();
if (typeof result === "number") {
return result + 1;
}
return undefined;
}
7.

What is the type of the invalid variable in the function below?

function outputMessage(message: string) {
if (typeof message === "string") {
console.log(message);
} else {
let invalid = message;
console.error(invalid);
}
}
8.

We have a variable that will hold a two-dimensional point. What is most appropriate type annotation for this?

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