The Weird Parts of TypeScript 13 exercises

Properly Typing an Object of Functions

Here we're working with an object called objOfFunctions, which contains functions keyed by string, number, or boolean. Each key has an associated function to process an input of that type:

const objOfFunctions = {
string: (input: string) => input.toUpperCase(),
number: (in

Loading exercise


00:00 In this exercise we have an object of functions and this object of functions basically has either string or number or boolean as the keys on it and each of the inputs correspond to that type so we have an input which is a string on the string one turns it to an uppercase in number it turns it to a two fixed two and with a boolean it takes in and it returns true or false so there's a bunch of formatters here really and then we have a format function down below which takes in input which can be string or number or boolean which

00:29 we extract out the input type which we just call type of input and this is by the way this is like the normal type of this is the one you're used to where if we don't constrain it using this as it actually ends up being kind of string or number or big into a boolean or simple or undefined or object or function and that's fine but we actually just want it to be constrained to these three things so we use the as to kind of like force TypeScript into that if we don't use it then it's going to yell at us for adding like possibilities like

00:59 indexing into object of functions to grab things that might not be there so we then grab our formatter from the object of functions and the formatter ends up being an array of a sorry a union of functions so it could be either this function with which takes a string this function which takes a boolean or sorry this function takes number or this function that takes a boolean you get the idea and we're getting an error your job is to try to figure out how we can solve this error because it's

01:29 kind of a nasty one and understand that we've kind of covered the information that you need for this already by looking at the way that when you call a union of functions you need to intersect the things that they require together I think you've got everything good luck