Notes

Typescript Notes

Edit on GitHub


JavaScript
2 minutes

Typescript originally was uber cool because it provided code encapsulation and modularity as well as types.

The code encapsulation in TS is not that big of a deal now since ES6 (ES2015) introduced Class syntax. The support for the syntax is a bit tricky though. Edge, Chrome and Node.js support everything, while Firefox does not support private class fields and Safari does not support private or public class fields, static or static class fields. IE is just dead, no Class support whatsoever.

Same is the case of modularity since ES6 also introduces Modules, where you can import and export code and it automatically uses strict mode.

Arrow functions have also been added to JS with ES6.

Type support is still cool though, because it gives you automatic documentation, kind of.

we can get the “nice and short” error message mentioning out Banana type if we use interface instead of type

Array of objects

Here’s an object of type List

1interface List {
2  id: number
3  title: string
4}

And we want an array Lists of objects List, which can be done the following two ways:

using an indexer

1// using an indexer
2interface Lists {
3  [index: number]: List
4}

and my preferred one

1interface Lists extends Array<List> {}

And now we can declare the interface like so

 1// Option A
 2var result: List[] = [
 3  { id: 0, label: 'CId', key: 'contentId' },
 4  { id: 1, label: 'Modified By', key: 'modifiedBy' },
 5  { id: 2, label: 'Modified Date', key: 'modified' },
 6  { id: 3, label: 'Status', key: 'contentStatusId' },
 7  { id: 4, label: 'Status > Type', key: ['contentStatusId', 'contentTypeId'] },
 8  { id: 5, label: 'Title', key: 'title' },
 9  { id: 6, label: 'Type', key: 'contentTypeId' },
10  { id: 7, label: 'Type > Status', key: ['contentTypeId', 'contentStatusId'] },
11]
12
13// Option B
14var result: Lists = [
15  { id: 0, label: 'CId', key: 'contentId' },
16  { id: 1, label: 'Modified By', key: 'modifiedBy' },
17  { id: 2, label: 'Modified Date', key: 'modified' },
18  { id: 3, label: 'Status', key: 'contentStatusId' },
19  { id: 4, label: 'Status > Type', key: ['contentStatusId', 'contentTypeId'] },
20  { id: 5, label: 'Title', key: 'title' },
21  { id: 6, label: 'Type', key: 'contentTypeId' },
22  { id: 7, label: 'Type > Status', key: ['contentTypeId', 'contentStatusId'] },
23]