Typescript Models and JavaScript Objects

John Peters - Jan 23 '20 - - Dev Community

Given a Javascript (JSON) Object like this:

Alt Text

The Typescript Model Equivalent

Alt Text

Morphing JSON objects to Strong Types

Alt Text

The JSON Object with a Name

Alt Text

Differences?

The variable test allows any object name and any value type. It has no contract on what it contains. Intellisense shows all properties on the 'test' object.

Conformity and Optional Values

The settingDisplay variable must conform to the settingDisplay class model. All property values must be of the type specified. If they are non conformant, an error at code-time is seen.

See the checked? variable in the Typescript model? This is an optional variable. It is the reason why the settingDisplay assignment did not need to specify it in the JSON object. Intellisense works here too.

Implicit Interfaces

The interface is implicitly defined within the class object, no need for a separate Interface definition.

The only time one may want to consider an Interface definition, is when functions require a specific type to work correctly. This is useful for testing in which the test can inject a mock object that follows the shape of the expected input. No Jasmine mocking needed when interfaces are used.

This is the essence of Typescript code-time type checking. Static type-checking saves time (majorly).

Just say no to run-time type error discovery. It's a colossal waste of time.

JWP2020

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Terabox Video Player