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.
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.
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.
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.
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.
- 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!
Posted on by: