The Utils Folder 10 exercises
Problem

Combining Generic Types with Generic Functions

Here we have safeFunction, which accepts a function func typed as PromiseFunc that returns a function itself. However, if func encounters an error, it is caught and returned instead:


type PromiseFunc = () => Promise<any>;
const safeFunction = (func: PromiseFunc) => async () => {

Loading exercise

Transcript

00:00 In this exercise, we're going to look at combining generic types and generic functions. We have a safe function here, which takes in a function of promise func, and it returns a function itself, which is an async func, in which we either call the result or call the function itself and return the result inside a try catch,

00:18 or if we get an error, we check if e is an instance of error and then return that error. That means then that the thing that we get back from the function should basically be either the thing that's returned or an error. So in this case, this function should be returning number or error,

00:37 whereas in fact it's returning promise any. Okay, that's a little bit strange. Down the bottom here, we have a safe function that always returns hello here, and so this one should be returning promise string or error. This result should be string or error in this case. Your job is to work out how to type safe function here,

00:56 how to add a generic type parameter to it, and then we might also need to get this promise func sorted as well. This part of it is correct. We never want to receive any parameters into this function, but the promise any looks a little bit dodgy there. So I think that's all the information you need. Good luck.