Check out a free preview of the full Deep JavaScript Foundations, v3 course

The "Custom Types" Lesson is part of the full, Deep JavaScript Foundations, v3 course featured in this preview video. Here's what you'd learn in this lesson:

Kyle defines what custom types are and explains how they can help to reduce type misassignments.

Preview
Close

Transcript from the "Custom Types" Lesson

[00:00:00]
>> Kyle Simpson: We can get much more sophisticated when we talk about function parameters and return values. You can define custom types like this. Here I'm defining that an object of a type that has a property called name that is of type string, that is a type. And then I can pass values of that type as parameters.

[00:00:19]
And I can receive values back as parameters. So here I am passing in studentRec of the type student. I'm defining my own type if you will. So it's much more powerful in that you can define these custom types. And this program, just to be clear, this program doesn't have any errors.

[00:00:38]
Because what it knows is that when I do line 4 a return of studentRec.name, it knows that studentRec was an object with a name property that was string. So it knows it's returning a string and when line 9 I try to assign it a string it knows everything is fine.

[00:00:52]
But you'll notice that most of the guarantee here is are things being assigned correctly. Are they being assigned the right types? A parameter to a function is a lot like a variable. If you're saying I wanna only be able to pass in numbers, then you're basically saying the same thing as I want this variable to only hold numbers.

[00:01:18]
>> Kyle Simpson: Where I to uses something like typescript I probably would define many more of my parameters as say union types. Or I would say, you know what, I'm gonna allow strings, numbers, and nulls. Because it's rare that I want it to be so restrictive that it can only ever receive exactly this kind of structured object for example.

[00:01:41]
But nevertheless, it's able to do some very useful guarantees if the problems that you have are misassignments of types.

Learn Straight from the Experts Who Shape the Modern Web

  • In-depth Courses
  • Industry Leading Experts
  • Learning Paths
  • Live Interactive Workshops
Get Unlimited Access Now