Learn TypeScript

Quiz

Quiz

Test your knowledge on generic types with this quiz.

1.

We have a type within our codebase for a comment:

type Comment = {
comment: string;
email: string;
}

What generic type can we use with Comment that would create a type equivalent to the type below:

type ReadonlyComment = {
readonly comment: string;
readonly email: string;
}
2.

The function below counts the occurrences of an item in an array:

function countDisinct(itemToCount, array) {
return array.filter(item => item === itemToCount).length
}

How can we make this strongly-typed?

function countDisinct<ItemType>(itemToCount: ItemType, array: ItemType[]) {
return array.filter(item => item === itemToCount).length
}
function countDisinct(itemToCount: ItemType, array: ItemType[])<ItemType> {
return array.filter(item => item === itemToCount).length
}
3.

We need to create a function to remove occurrences of an item from an array. It needs to be strongly-typed and work with arrays containing any primitive type. Here’s our attempt:

function remove<ItemType>(itemToRemove: ItemType, array: Array<ItemType>): ItemType {
return array.filter(item => item !== itemToRemove);
}

Can you identify the error in the above code?

function remove(itemToRemove: ItemType, array: Array<ItemType>)<ItemType>: ItemType {
return array.filter(item => item !== itemToRemove);
}
4.

We have the following interface which represents a user:

interface User {
id: any;
name: string;
email: string
}

How can we improve this by removing the any type on the id property and letting the consumer of the interface supply its type?

interface User {
id: string | number;
name: string;
email: string
}
interface <UserIdType>User {
id: UserIdType;
name: string;
email: string
}
interface User<UserIdType> {
id: UserIdType;
name: string;
email: string
}
5.

We need to extend the generic list class we created in the last lesson. As a reminder, here’s the class:

class List<ItemType> {
private items: ItemType[] = [];
add(item: ItemType) {
this.items.push(item);
}
}

We need to add a method called getNth which returns the array item at the nth position in the list. How could we implement this?

getNth(n: number) {
return this.items[n];
}
getNth(n: number): ItemType[] {
return this.items[n];
}
getNth(n: ItemType) {
return this.items[n];
}
6.

We have a function below which outputs the name property of an object to the console. How can we use generics to make this more strongly-typed?

function logName(object: any) {
console.log("My name is " + object.name);
}
function logName<T>(object: T) {
console.log("My name is " + object.name);
}
function logName<T extends {name: string}>(object: T) {
console.log("My name is " + object.name);
}

Prev

Spreading generic tuple parameters

Next

Introduction

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