Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

typescript enablement wip" #27

Draft
wants to merge 2 commits into
base: master
Choose a base branch
from
Draft
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
294 changes: 255 additions & 39 deletions content/articles/typescript.md
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
---
title: Introduction to Typescript
title: Introduction to TypeScript
subtitle: Introducing types to JavaScript.
date: 2017-09-12T05:00:00.000Z
authors:
author1:
name: Philip Double
name: Spencer Stolworthy
avatar: philip.double.png
time: 1 hour
difficulty: easy
Expand All @@ -14,60 +14,276 @@ tags:
order: 4.4
---

## What is it?
# What is TypeScript?

Value Stream Mapping (VSM) and Metrics-Based Process Mapping (MBPM) are third generation lean process improvement techniques, optimized for an extended organizational transformation effort. They work in tandem, where VSM is designed to view the big, macro picture and make strategic decisions with executives, and MBPM is designed to view the detailed, micro picture and make tactical improvements with front line workers. The first generation of these techniques comes from Toyota's "information and material flow" (as documented in Lean Thinking[<sup>1</sup>](#footnote-1) and the second generation from Learning to See[<sup>2</sup>](#footnote-2).
## Introduction

## Why use VSM & MBPM?
TypeScript is an extension of JavaScript that adds support for static typing. TypeScript is designed to aid in the development of large client-side and server-side applications. TypeScript transpiles to JavaScript, which means TypeScript source code can be converted to Javascript source code with the use of a transpiler such as Babel or TypeScript Checker.

In the context of software delivery, VSM & MBPM are excellent tools to holistically analyze and optimize "brownfield" delivery processes, including everything from requirements definition, infrastructure provisioning and application development.
## Static Typing

Being derived from Lean Manufacturing, VSM & MBPM visually represent the way work flows through an organization, at both a macro and micro level, from the time a customer requests a good/service, until the time a customer receives the good/service. When used together, these tools are particularly effective at:
Static typing is the process of ensuring that all data that flows through an application meets an expected type definition.
By default, JavaScript is a dynamically typed language.
This means that a variable's type is inferred at runtime rather than defined beforehand.

* Building shared understanding throughout the various levels of an organization on how work is actually done
* Creating the urgency for improvement
* Formulating specific, data driven improvement plans
* Preventing "improvement" work in a particular area that leads to sub-optimization for the entire value stream / process
Let's look at some code, in JavaScript, you can define a variable without
explicity defining its type. For example, you can define a variable and Javascript
and provide an initial value. Alternatively, you can define a variable in Javascript
and not initialize it, then assign it a value later. All of this can be done without specifying a type for the variable.

## Facilitation Materials Needed
#### Javascript

Some teams prefer whiteboards, but the most common approach uses paper and PostIts
```JavaScript
// Define count and initialize it with a value
var count = 0

* Drawing paper roll[<sup>3</sup>](#footnote-3).
* Different colored wide format sticky notes like the 4x6 sticky notes[<sup>4</sup>](#footnote-4)
* Markers for the PostIts
* Charcoal pencil and eraser[<sup>5</sup>](#footnote-5) to draw lines between PostIts
* For MBPM; chalk line can be useful, but not required
// Define denominator and provide no initial value
var denominator

## How does it fit?
// Set denominator equal to a value
denominator = 2
```

Both VSM & MBPM document a current state map, and then design a future state map for subsequent implementation.
#### TypeScript

* The current state map is typically done in the Why area of the Discovery of the Open Practice Library.
* The future state map is typically done as part of the Outcomes area of the Discoery of the Open Practice Library.
```TypeScript
let count: number = 0

## Additional Resources
let denominator: number
denominator = 2
```

### Start With
Notice that you annotate the variable's type when declaring it in TypeScript. Let's modify our previous code just a bit.

* [Webinar](https://vimeo.com/149407030) and [Slides](https://www.slideshare.net/KarenMartinGroup/vsmmbpmwhenyouoptforeach) from Karen Martin's Value Stream Mapping and Process Mapping: When to Use Each
#### Javascript

### VSM Specific Resources
```Javascript
let count = 0
count++ // count == 1
count = "hello" // count = "hello"
count++ // count == NaN
```

* [Book](https://www.ksmartin.com/books/value-stream-mapping/) by Karen Martin and Mike Osterling
* [List of Webinars](https://www.ksmartin.com/webinar/value-stream-mapping/) by Karen Martin
* [Value Streams are Made of People](https://lizkeogh.com/value-streams-are-made-of-people/) by Liz Keogh
Uh-oh. We assigned a string to count. Then, when we tried to increment count, the operation returned `NaN`.
Now, this example may seem contrived, but this is actually a common problem, and it is one of the main problems that a statically typed language can help solve.

### MBPM Specific Resources
Let's look at the same code in TypeScript:

* [Webinar](https://vimeo.com/54601924) and [Slides](https://www.slideshare.net/KarenMartinGroup/metricsbased-process-mapping-what-when-how) from Karen Martin's Metrics-Based Process Mapping: What, When & How
* [List of Webinars](https://www.ksmartin.com/webinar/metrics-based-process-mapping/) by Karen Martin
```TypeScript
let count: number = 0
count++ // count == 1
count = "hello" // count = "hello"
count++ // count == NaN
```

## External References
Great, not much changed... or so it seems. When you attempt to transpile this code,
the TypeScript transpiler will raise an error, and point you back to the line where the error occurs.
Additionally, if you are using an advanced text editor or IDE, you will see error highlights and descriptions explaining that this code will not work as expected.

1. <a name="footnote-1"></a>[Lean Thinking](https://www.lean.org/BookStore/ProductDetails.cfm?SelectedProductID=88)
2. <a name="footnote-2"></a>[Learning to See](https://www.lean.org/Bookstore/ProductDetails.cfm?SelectedProductId=9)
3. <a name="footnote-3"></a>[Drawing Paper example](http://www.ikea.com/us/en/catalog/products/80324072/)
4. <a name="footnote-4"></a>[4x6 sticky notes example](https://www.amazon.com/Post-Sticky-Janeiro-Collection-4621-SSAU/dp/B001UXFT70)
5. <a name="footnote-5"></a>[charcoal pencil and eraser example](https://www.amazon.com/Studio-25-Piece-Drawing-Artists-Charcoal/dp/1441310207)
6. <a name="footnote-6"></a>[Double Diamond design model](https://medium.com/digital-experience-design/how-to-apply-a-design-thinking-hcd-ux-or-any-creative-process-from-scratch-b8786efbf812)
This example is simple, but starts to demonstrate the power of static typing.

Great, not much changed... or so it seems. When you attempt to transpile this code,
the TypeScript transpiler will raise an error, and point you back to the line where the error occurs.
Additionally, if you are using an advanced text editor or IDE, you will see error highlights and descriptions explaining that this code will not work as expected.

This example is simple, but starts to demonstrate the power of static typing.

## Mental Load

Beyond static type checking, TypeScript helps reduce mental load on developers.
When types are statically defined, it is easier to comprehend data shapes, and visualize how data is flowing through the application.
This benefit applies to new developers brought onto the project, as well as current developers who are reviewing merge requests
or loading the project into their mental RAM at the start of a workday.

Let's say we are TMDb and we want to store information about movies. We might come up with an object that looks similar to this:

```JSON
{
"adult": false,
"backdrop_path": "/fCayJrkfRaCRCTh8GqN30f8oyQF.jpg",
"belongs_to_collection": null,
"budget": 63000000,
"genres": [
{
"id": 18,
"name": "Drama"
}
],
"homepage": "",
"id": 550,
"imdb_id": "tt0137523",
"original_language": "en",
"original_title": "Fight Club",
"overview": "A ticking-time-bomb insomniac and a slippery soap salesman channel primal male aggression into a shocking new form of therapy. Their concept catches on, with underground \"fight clubs\" forming in every town, until an eccentric gets in the way and ignites an out-of-control spiral toward oblivion.",
"popularity": 0.5,
"poster_path": null,
"production_companies": [
{
"id": 508,
"logo_path": "/7PzJdsLGlR7oW4J0J5Xcd0pHGRg.png",
"name": "Regency Enterprises",
"origin_country": "US"
},
{
"id": 711,
"logo_path": null,
"name": "Fox 2000 Pictures",
"origin_country": ""
},
{
"id": 20555,
"logo_path": null,
"name": "Taurus Film",
"origin_country": ""
},
{
"id": 54050,
"logo_path": null,
"name": "Linson Films",
"origin_country": ""
},
{
"id": 54051,
"logo_path": null,
"name": "Atman Entertainment",
"origin_country": ""
},
{
"id": 54052,
"logo_path": null,
"name": "Knickerbocker Films",
"origin_country": ""
},
{
"id": 25,
"logo_path": "/qZCc1lty5FzX30aOCVRBLzaVmcp.png",
"name": "20th Century Fox",
"origin_country": "US"
}
],
"production_countries": [
{
"iso_3166_1": "US",
"name": "United States of America"
}
],
"release_date": "1999-10-12",
"revenue": 100853753,
"runtime": 139,
"spoken_languages": [
{
"iso_639_1": "en",
"name": "English"
}
],
"status": "Released",
"tagline": "How much can you know about yourself if you've never been in a fight?",
"title": "Fight Club",
"video": false,
"vote_average": 7.8,
"vote_count": 3439
}
```

Source: [TMDb](https://developers.themoviedb.org/3/movies/get-movie-details)

Woah... that's a lot of information. It's a lot of information that some poor developer is going to have to load into their head each time they work on a feature that implements this data.

TypeScript itself is not a panacea to this problem, but when combined with good coding practices and a modern text editor or IDE, TypeScript can help some of the pains involved with working with external data.

Using TypeScript, we can define what this data will look like. Then, as we use the data, the TypeScript compiler will help us find places we may have used it wrong.
Additionally, our IDE or text editor will be able to provide hints about the object's definition while we write code.

In TypeScript, we could create an `interface` for this particular object shape.

```TypeScript
export interface Language {
iso_639_1: string
name: string
}
export interface Country {
iso_3166_1: string
name: string
}
export interface Company {
id: string
logo_path: string
name: string
origin_country: string
}
export interface Genre {
id: number
name: string
}
export enum Status = {
Released,
PostProduction,
}
export interface Movie {
spoken_languages: Array<Language>
production_countries: Array<Country>
production_companies: Array<Company>
overview: string
id: string
original_language: Language
budget: number
genres: Array<Genre>
popularity: number
poster_path?: string
backdrop_path?: string
homepage?: string
release_date: Date
revenue: number
status: Status
title: string
tagline: string
vote_average: number
vote_count: number
}
```

Defining an interface for our movie makes it easier to understand what each field means, and what data it is expecting. Note that in the example above some of the fields would need to be [serialized](https://en.wikipedia.org/wiki/Serialization) in order to meet the interface.

Now that we have the interface defined, we can see how it would be used in a real application.

Let's say we have a simple movie service that fetches a list of movies:

```typescript
function getMovies(): Promise<Array<Movie>> {
return fetch('movies.example.com').then((response) =>
response.json()
) as Array<Movie>
}
```

Notice that we can add a return type to our function. So now any client code that calls our `getMovies` function will know that it returns a promise of a list of `Movie`.

Because the method has a typed return, many modern IDEs will provide code hints and typing completion. This speeds up development time.

## The cons of TypeScript

TypeScript does have some drawbacks, and it is worth weighing these against the pros to determine if it is a good fit for the project you are working on.

### Increased boilerplate

In order to take advantage of static typing, additional code must be written to actually define types in advanced.
In small projects or rapid prototypes, this additional work can minimize the positive impact TypeScript can have on a project. This is especially true if members of the team are not familiar with TypeScript and will need to learn its syntax.

### False sense of security

Statically typed languages can often give a false sense of security about the quality or reliability of a codebase. Frequently, using TypeScript can be erroneously billed as a replacement for adequate testing. This beleif is incorrect.

There is no adequate replacement for proper testing. That an TypeScript application properly transpiles and gives no errors is not an indication that the codebase is bug free.

The TypeScript compiler can also be silenced or confused, both intentionally and unintentionally.
For example, any variable can be coerced to a type of `unknown`. From there, it can be coerced to any other type...
including `any`. This practice can be legitimately used in some cases, but it can also be a code smell.

Additionally, when using APIs external to the codebase, contracts can change unexpectedly. Therefore, TypeScript does not eliminate the need proper error handling.

### Package support

It is hard to overstate the wide package support for TypeScript in the JavaScript ecosystem.
A vast plurality of packages have support for TypeScript already built in, or installable in another package.
However, when a package does not have support for TypeScript out of the box, it can be laborious to include it in a project.
This concern really should be quite minimal, however, it is worth considering whether you and your team are willing to tolerate or mitigate a lack of TypeScript support from third parties.