Default Parameter Types for Generic Functions
We're back with the createStringMap
function which is now generic, meaning it can handle a variety of types:
const createStringMap = <T>() => {
return new Map<string, T>();
};
When calling createStringMap
without a type argument, the type T
defaults to unknown
:
const
Transcript
00:00 We're back with our createStringMap function. Inside here we have a string map where we're saying string map and createStringMap and we're not passing in a type argument. You notice here we don't need to pass in a type argument to a generic function if we don't want to. This is different from a generic type. So we've got our string map here
00:18 and currently map is mapString unknown. But actually, if we don't pass in a value for T, we want to default it. We want it to default to string. So if we don't pass in anything here, down here we're passing a number, down here we're passing a number, still working as before. But if we don't pass in anything,
00:36 we don't want it to default to unknown as it currently is, we want to default it to string. Your job is to try to figure out how we can annotate createStringMap, especially this first line up here, so that T defaults to string.