The Utils Folder 10 exercises
solution

Setting a Default Parameter Type for Generic Functions

The syntax for setting default types for generic functions is the same as for generic types:

const createStringMap = <T = string>() => {
  return new Map<string, T>();
};

By using the T = string syntax, we tell the function that if no type argument is supplied, it should default to `

Loading solution

Transcript

00:00 So the syntax is actually exactly the same as we saw in generic types. This T here, we can say equals string. And now if we don't pass in a value for createStringMap here, it defaults to string, if we don't pass in a type argument. There we go, beautiful. So now we have mapString string.

00:18 We can, of course, make this anything we want to. We can say T equals number here. And now the values for this is going to be mapString number instead. So this equals is basically a way of changing what the default type is going to be when you don't pass in a type argument.

00:34 Very, very useful, and it's nice that it's exactly the same syntax as in generic types too.