You can even add new properties on the fly. The fact that ES 5 only defines six data types may surprise you, since you've probably used a lot of other types such as Date and RegExp, etc., but those are all just different kinds of objects. Perhaps the most important object types are functions and arrays. Functions are regular objects, in that they're a collection of properties just like any other object, but the aspect that sets them apart from all other objects is that they contain logic that can be executed.
In this example, I've defined three different properties, and assigned them all values. I've also separated all the values with a comma and a line break, though white space doesn't matter when defining object literals, which means that I could remove all the spaces and line breaks and end up with this. It's true that this would be the exactly the same object, but it's far less readable, so let's add them back before I get a headache. Now that I can see the object clearly again, let's go to the next step and give this object some behavior by defining a function. As I mentioned earlier, functions are just regular values, so I can define and assign them in exactly the same way that I assign other values.
Again, whitespace doesn't matter. I can put the whole function definition on one line like this, or I can spread it across multiple lines. It's really up to me. Now that I have this object, I can do things with it like it assign it to a variable and pass it to a function. Notice how the function just calls the speak method on the object that it's given. This is a great example of duck typing in action. The function doesn't check to see if the object is a certain type or if the method exists before calling it. It just calls the method and assumes the code that passed the object in knew what they were doing.
- What is TypeScript?
- Installing TypeScript
- Creating a TypeScript project
- Reviewing ES6 language features
- Defining custom and anonymous types
- Defining and implementing TypeScript classes
- Working with generics
- Organizing code with namespaces
- Switching modules
- Importing modules
- Debugging TypeScript
- Implementing decorators