Classes 9 exercises

Dive into Classes with Type Predicates

Continuing our dive into classes, let's look at a spot where you might need to use a type predicate.

We have a class called Form that takes a generic type of TValues. Inside the constructor is a public property called values and a private function called validate:

class Form<

Loading exercise


0:00 We're going to continue our dive into classes here by looking at a spot where you might need to use a type predicate. We have a class form here which takes in a generic of Tvalues. Inside the constructor here, we have a public values is TValues, and then a private validate function.

0:18 This syntax is just like, it automatically assigns it to a public property of values. If I remove this, then if we had public values TValues, then I would basically have to assign this. This.values, can't type, equals values.

0:37 That's basically a shorthand for that, where I can just say public values and it automatically gets put on the class. Very useful. I have a couple of little bits down here. I have an isInvalid function, which basically calls the validate function which the user passes to the class.

0:55 Then what it does is it returns a result which might be string or it might be nothing. This is going to be basically the error message. If the result is a string, then we set the error to the result and we return true. Otherwise, we say this.error is undefined and return .

1:10 This.invalid, when it's used, you can see an example of usage here. I've got a username and password form. If there's no username, we return username is required, otherwise we return password is required if there's nothing like that.

1:24 Then inside this if statement here, we're checking if the form is invalid. If the form is invalid, we should really expect form.error here to be a string, but instead it's string or undefined. If it's not invalid, then we would expect it to be form.error.

1:42 We expect it to be as it is, string or undefined. What I want you to do is find a way to type this isInvalid function so that it behaves like a type predicate. eExcept what it's asserting on, you're not passing anything in here.

2:00 You're actually going to be asserting on this, and that's a big clue that this. Good luck. This is an interesting one. You're going to I think learn some new syntax here. It's fairly funky.