Advanced concepts like interfaces and decorators are introduced.
10. Simple Refactoring
To kick off the second half, I start with a simple refactoring. I add a
debugDelay method to simplify messages I am logging for tracing purposes.
12. Recursive Print
The interface is extended to include an optional property. Create a generic function that takes any item that implements
ICanPrint and recursively calls
print() on the item and the function on its children (if they exist). A read-only property is implemented using a “getter” on the
ContactList class, then the code is refactored to use the recursive print function.
13. Format the Print Output
A few helper functions format the print by making it possible to pass a property and output a label with its corresponding value. The code is refactored to use the new functions and a new defect appears; name is no longer printing and shows as
undefined. Fortunately, TypeScript is ready to fix it in the next iteration.
14. Key Types to the Rescue
TypeScript supports a special convention
keyof (called an “index type”) that will inspect the signature of a class or interface, then create a list of allowed string values based on that signature. In this step, a custom key type is created for properties of
IAmContact. This immediately reveals the defect and provides an auto-completion suggestion to fix it.
15. Type Guards
16. Strict Types
17. Type Decorators
Decorators are one of the most powerful aspects of TypeScript. They enable aspect-oriented development. You can create a piece of functionality, or a “behavior”, and apply that behavior to code using attributes. If you’ve done any Angular development, decorators are used extensively in the framework. See how to build and apply your own decorator in this step.
18. Compilation Targets
- How it works in the TypeScript world
- The flexibility of TypeScript
- The benefits TypeScript brings including finding and auto-suggesting fixes for common defects before your code reaches production
I’m curious to hear your thoughts and feedback, so please feel comfortable sharing them in the comments below!