Type Parameter Constraints with Generic Functions
In this exercise, we'll examine constraints in type parameters for generic functions.
more specifically in the context of a function named addCodeToError
. This function utilizes a type parameter TError
and strives to incorporate a code
property to the TError
object that is passed in.
Cons
Transcript
00:00 In this exercise, we're going to look at constraints in type parameters in generic functions. We have an addCodeToError function here, which is taking in a type parameter of tError. And then it's basically saying the thing that we're passing in is going to be tError. Error is tError.
00:17 And so, the way we're trying to use this function is we're trying to say, sure, we've got our addCodeToError function. We pass in an error here, and we're expecting the thing that we get back is going to have a code added to it. So the runtime code should just be working here. Nice. And we're also expecting that we get a message property on there as well.
00:37 So we want basically two constraints here. Well, the constraint that we really want is we want to say whatever tError is, we need to make sure that it might have a code on it, and it must have a message on it as well. Might have a code, must have a message.
00:57 So this way, we can make sure that things we're passing into addCodeToError correspond to the thing we expect errors to be. We expect them to have a message. And it means that this runtime code in the middle, because currently it doesn't exist on type tError, because tError could be anything. So that's your job, is to try to change the type signature of addCodeToError
01:15 to make sure that we're constraining tError to something that has a message and might have a code.