| 
  
   Size: 7681 
  
  Comment:  
 | 
    ← Revision 75 as of 2025-01-24 18:34:08  ⇥ 
  Size: 21500 
  
  Comment:  
 | 
| Deletions are marked like this. | Additions are marked like this. | 
| Line 1: | Line 1: | 
| <<TableOfContents(2)>> | |
| Line 5: | Line 6: | 
| == install == npm install -g typescript == Compile == tsc helloworld.ts  | 
Typescript is a typed superset of [[Javascript]] that transpiles (is converted) to plain [[Javascript]]. == Install, compile and run == {{{#!highlight sh sudo npm install -g typescript # install echo "console.log(\"Hello world\");" > helloworld.ts tsc helloworld.ts # compile node helloworld.js # run }}}  | 
| Line 13: | Line 18: | 
| {{{ | {{{#!highlight bash | 
| Line 157: | Line 162: | 
| {{{ | {{{#!highlight bash | 
| Line 163: | Line 168: | 
| {{{ | {{{#!highlight html | 
| Line 171: | Line 176: | 
//lib.ts  | 
}}} === lib.ts === * https://www.typescriptlang.org/docs/handbook/modules.html Any declaration (such as a variable, function, class, type alias, or interface) can be exported by adding the export keyword. {{{#!highlight javascript  | 
| Line 176: | Line 188: | 
| }}} | |
| Line 178: | Line 191: | 
| {{{ |  * import {xyz} from "module"; {{{#!highlight javascript  | 
| Line 187: | Line 202: | 
|     return "Hello GP, " + p.firstName + ' ' + p.lastName + ' '  + getText() ;  | 
return "Hello GP, " + p.firstName + ' ' + p.lastName + ' ' + getText() ; | 
| Line 205: | Line 219: | 
| {{{ | {{{#!highlight javascript | 
| Line 220: | Line 234: | 
| {{{ | {{{#!highlight javascript | 
| Line 232: | Line 246: | 
=== build === {{{  | 
=== build.sh === {{{#!highlight bash  | 
| Line 238: | Line 251: | 
== ReactJS + typescript example == https://reactjs.org/ A [[Javascript]] library for building user interfaces. Build encapsulated components that manage their own state, then compose them to make complex UIs. https://reactjs.org/docs/thinking-in-react.html '''Structure''' {{{#!highlight bash . ├── App.tsx ├── build.sh ├── greeter.html ├── greeter.tsx ├── lib.ts ├── NameHolder.tsx ├── package.json ├── tsconfig.json └── webpack.config.js }}} === webpack.config.js === {{{#!highlight javascript var path = require('path'); module.exports = { entry: {main:'./greeter.js'}, resolve: { extensions: ['.js', '.jsx', '.ts', '.tsx'] }, output: { filename: 'bundle.js', path: path.resolve(__dirname, 'dist') } }; }}} === tsconfig.json === {{{#!highlight javascript { "compilerOptions": { "module": "es2015", "target": "es5", "noImplicitAny": true, "removeComments": true, "preserveConstEnums": true, "sourceMap": true, "moduleResolution": "node", "allowSyntheticDefaultImports": true, "jsx": "react" } } }}} === lib.ts === {{{#!highlight javascript function getText() { return "text"; } interface Person { firstName: string; lastName: string; } function greeterPerson(p: Person) { return "Hello GP, " + p.firstName + ' ' + p.lastName + ' ' + getText(); } function greeter(person: string) { return "Hello, " + person; } interface HumanInterface { name: string; getName(): void; } class Human implements HumanInterface { name: string; constructor(name: string) { this.name = name; } getName() { return "My name is " + this.name; } } class PubSub { callbacks: Function[]; constructor() { this.callbacks = []; } addListener(fn: Function): void { this.callbacks.push(fn); } notify(message: string): void { this.callbacks.forEach((fn) => { fn(message); }); } } let pubSub = new PubSub(); export { greeter, greeterPerson, Human, HumanInterface, Person, getText, PubSub, pubSub } }}} === greeter.html === {{{#!highlight html <!DOCTYPE html> <html> <head><title>React + typescript test</title><meta charset="UTF-8"></head> <body> <div id="app"></div> <script src="dist/bundle.js"></script> </body> </html> }}} === package.json === {{{#!highlight javascript { "name": "test", "private": true, "version": "0.0.0", "devDependencies": { "@types/react": "15.0.35", "@types/react-dom": "15.5.1", "@types/webpack-env": "1.13.0", "react": "15.6.1", "react-dom": "15.6.1", "typescript": "2.4.1", "webpack": "2.5.1" } } }}} === App.tsx === {{{#!highlight javascript import React, { ReactChild } from 'react'; import { Person, greeterPerson, Human, HumanInterface } from './lib'; import NameHolder from './NameHolder'; import { pubSub } from './lib'; interface MyState { currDate: string; greetings: string; human: HumanInterface; } function createMyState(currDate: string, greetings: string, human: HumanInterface): MyState { return { currDate: currDate, greetings: greetings, human: human }; } interface MyProps { prop: string; } export default class App extends React.Component<MyProps, MyState> { text: string; timerID: number; constructor(props: MyProps) { super(props); this.text = this.props.prop; this.state = createMyState("waiting for date", "waiting for greetings", null); // init with MyState format } public static createHuman(name: string): HumanInterface { return new Human(name); } public tickHandler() { let cd = new Date().toString(); let greetings = greeterPerson({ firstName: "first", lastName: "last" }); let human: HumanInterface = App.createHuman("JohnDoe"); this.setState(createMyState(cd, greetings, human)); } componentDidMount() { // called after the 1st render ! console.log("First render"); this.timerID = setInterval(this.tickHandler.bind(this), 1000); } componentWillUnmount() { // component will be destroyed console.log("Will be destroyed soon"); clearInterval(this.timerID); } public render() { // do not call set state in render ! return ( <div> <p>Hello World!!! -- {this.text} -- {this.state.greetings}</p> <p>Human {this.state.human != null ? this.state.human.getName() : ""} {this.state.currDate} </p> <p> <NameHolder attr="holding..." /> </p> <p> <NameHolder attr={this.state.currDate} /> </p> <div onClick={() => { this.clickHandler(); }} > {this.props.children} </div> </div> ); } public clickHandler() { console.log("clicked. # children " + React.Children.count(this.props.children)); React.Children.forEach(this.props.children, (argx: any) => { if (argx.hasOwnProperty("props")) { console.log("props property found"); pubSub.notify("message from outer space !"); } console.log(JSON.stringify(argx)); }); } } }}} === greeter.tsx === {{{#!highlight javascript import React from 'react'; import ReactDOM from 'react-dom'; import {getText} from "./lib"; import App from './App'; // uses App.tsx import NameHolder from './NameHolder'; console.log("Entry point"); let appContainer = document.getElementById('app') ; let markup = <App prop="Other text inside the page"> <NameHolder attr="NameHolder child inside App "/> </App>; ReactDOM.render( markup , appContainer); }}} === NameHolder.tsx === {{{#!highlight javascript import React from 'react'; import { pubSub } from './lib'; // Component properties (XML attributes) interface NameHolderProperties { attr: string; } interface NameHolderState { attr: string; } // properties and state export default class NameHolder extends React.Component<NameHolderProperties, NameHolderState> { constructor(props: NameHolderProperties) { super(props); // populates the this.props this.state = { attr: this.props.attr }; pubSub.addListener(this.onMessage); } public render() { return <span>!!!{this.state.attr}!!!</span>; } public onMessage(message: string): void { console.log(this.state.attr + " receiVed " + message); } } }}} === build.sh === {{{#!highlight bash PATH=$PATH:./node_modules/typescript/bin echo Delete dist folder rm -rf dist echo Install NPM packages npm install echo Compile project tsc echo Create application bundle nodejs ./node_modules/webpack/bin/webpack.js --config webpack.config.js }}} == Constants == {{{#!highlight javascript export class Constants { static readonly CONST_A = "constA"; static readonly CONST_B = "constB"; } export const STATES = { stateA: 's1', stateB: 's2' }; }}} == Console app hello world == {{{#!highlight bash cd /tmp mkdir bar cd bar npm init echo '{ "compilerOptions": { "target": "es5", "sourceMap": true } }' > tsconfig.json npm install typescript ts-node npm install @types/node echo -e '#!/usr/bin/env node\nconsole.log("Hello world!");' > index.ts ./node_modules/ts-node/dist/bin.js index.ts }}} == Promise == * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise * The Promise object represents the eventual completion (or failure) of an asynchronous operation and its resulting value. * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Using_promises * A Promise is an object representing the eventual completion or failure of an asynchronous operation. * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/all * The Promise.all() method takes an iterable of promises as an input, and returns a single Promise that resolves to an array of the results of the input promises. * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/allSettled * The Promise.allSettled() method returns a promise that resolves after all of the given promises have either fulfilled or rejected, with an array of objects that each describes the outcome of each promise. === index.ts === {{{#!highlight javascript #!/usr/bin/env node let p1:Promise<boolean> = new Promise<boolean>( (resolve,reject)=>{ resolve(true); } ); p1.then( (value)=>{ console.log("resolve sent value " + value ); } ) let c1:Promise<boolean> = new Promise<boolean>( (resolve,reject)=>{ reject('Error occurred'); } ); c1.catch( (value)=>{ console.log("reject sent value " + value); } ); console.log("Hello world!"); }}} * ./node_modules/ts-node/dist/bin.js index.ts {{{ Hello world! resolve sent value true reject sent value Error occurred }}} * node_modules/typescript/bin/tsc index.ts * node index.js == Question mark after interface member name == * It means that the member is optional {{{#!highlight javascript interface Test{ memberx?:string; } }}} == Exclamation mark after interface member name == * It means that the member is required (not null) {{{#!highlight javascript interface Test{ memberx!:string; } }}} == Method not implemented == {{{#!highlight javascript throw new Error("Method not implemented."); }}} == RxJS == * https://rxjs.dev/guide/subject * An RxJS Subject is a special type of Observable that allows values to be multicasted to many Observers. {{{#!highlight bash sudo apt install nodejs npm -y node -v # v14.19.1 cd /tmp mkdir bar cd bar npm init echo '{ "compilerOptions": { "target": "es5", "sourceMap": true } }' > tsconfig.json npm install typescript ts-node @types/node rxjs }}} === index.ts === {{{#!highlight javascript #!/usr/bin/env node import { Observable, Subject, pipe, take, Subscription } from 'rxjs'; const publisher = new Observable(subscriber => { subscriber.next(1); subscriber.next(2); subscriber.next(3); setTimeout(() => { subscriber.next(4); subscriber.complete(); }, 1000); }); console.log("Hello world!"); publisher.subscribe({ next(x) { console.log('got value ' + x); }, error(err) { console.error('something wrong occurred: ' + err); }, complete() { console.log('done'); } }); let eventStream = new Subject(); // only consumes 2 events let obs1 = eventStream.pipe(take(2)) let subs1: Subscription = obs1.subscribe({ next: (x) => { console.log('Sub1 next: ' + x); }, error: (err) => { console.log('Sub1 error: ' + err); }, complete: () => { console.log('Sub1 completed'); console.log(`In complete closed subs1 ${subs1.closed}`); subs1.unsubscribe(); } }); const subscription2: Subscription = eventStream.subscribe({ next: (x) => { console.log('Sub2 next: ' + x); }, error: (err) => { console.log('Sub2 error: ' + err); }, complete: () => { console.log('Sub2 completed'); } }); // send notifications setTimeout(() => { eventStream.next('n1_foo'); eventStream.next('n2_foo'); eventStream.error('e1_foo'); eventStream.error('e2_foo'); eventStream.complete(); console.log(`Closed subs1 ${subs1.closed}`); }, 3000); }}} {{{#!highlight sh ./node_modules/ts-node/dist/bin.js index.ts ./node_modules/typescript/bin/tsc index.ts node index.js }}} == Enums == Using an enum is simple: just access any member as a property off of the enum itself, and declare types using the name of the enum. * https://www.typescriptlang.org/docs/handbook/enums.html#string-enums * https://www.typescriptlang.org/docs/handbook/enums.html#numeric-enums {{{#!highlight javascript enum Direction { Up=0, Down, Left, Right, } enum Direction { Up = "UP", Down = "DOWN", Left = "LEFT", Right = "RIGHT", } enum BooleanLikeHeterogeneousEnum { No = 0, Yes = "YES", } }}} == Microtask == * https://developer.mozilla.org/en-US/docs/Web/API/HTML_DOM_API/Microtask_guide * https://developer.mozilla.org/en-US/docs/Web/API/queueMicrotask == Date and epoch == {{{#!highlight javascript let d: Date = new Date(); console.log(">>> " + d.getTime() ); }}} == Nullish coalescing operator (??) (double question marks) == * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Nullish_coalescing_operator The '''nullish coalescing operator (??)''' is a logical operator that returns its right-hand side operand when its left-hand side operand is null or undefined, and otherwise returns its left-hand side operand.  | 
Contents
- 
typescript
- Install, compile and run
 - kate
 - Sample code typescript for browser
 - ReactJS + typescript example
 - Constants
 - Console app hello world
 - Promise
 - Question mark after interface member name
 - Exclamation mark after interface member name
 - Method not implemented
 - RxJS
 - Enums
 - Microtask
 - Date and epoch
 - Nullish coalescing operator (??) (double question marks)
 
 
typescript
Typescript is a typed superset of Javascript that transpiles (is converted) to plain Javascript.
Install, compile and run
kate
https://github.com/PrettyFlower/KateTypeScriptSyntaxHighlighting
With let keyword added
   1 <?xml version="1.0" encoding="UTF-8"?>
   2 <!DOCTYPE language SYSTEM "language.dtd">
   3 <language name="TypeScript" section="Scripts" extensions="*.ts;"
   4         indenter="cstyle" author="PrettyFlower (abigchode@gmail.com)">
   5 <highlighting>
   6     <list name="keywords">
   7         <item> if </item>
   8         <item> else </item>
   9         <item> for </item>
  10         <item> in </item>
  11         <item> while </item>
  12         <item> do </item>
  13         <item> continue </item>
  14         <item> break </item>
  15         <item> with </item>
  16         <item> try </item>
  17         <item> catch </item>
  18         <item> finally </item>
  19         <item> switch </item>
  20         <item> case </item>
  21         <item> new </item>
  22         <item> var </item>
  23         <item> function </item>
  24         <item> return </item>
  25         <item> delete </item>
  26         <item> true </item>
  27         <item> false </item>
  28         <item> void </item>
  29         <item> throw </item>
  30         <item> typeof </item>
  31         <item> const </item>
  32         <item> default </item>
  33         <item> this </item>
  34         <item> null </item>
  35         <item> undefined </item>
  36         
  37         <item> class </item>
  38         <item> export </item>
  39         <item> declare </item>
  40         <item> module </item>
  41         <item> import </item>
  42         <item> static </item>
  43         <item> interface </item>
  44         <item> implements </item>
  45         <item> constructor </item>
  46         <item> public </item>
  47         <item> private </item>
  48         <item> string </item>
  49         <item> number </item>
  50         <item> bool </item>
  51         <item> any </item>
  52         <item> extends </item>
  53         <item> let </item>
  54     </list>
  55     
  56     <contexts>
  57         <context attribute="Normal Text" lineEndContext="#stay" name="Normal">
  58             <DetectSpaces/>
  59             <keyword attribute="Keyword" context="#stay" String="keywords"/>
  60             <DetectChar attribute="String" context="String" char="""/>
  61             <DetectChar attribute="String Char" context="String 1" char="'"/>
  62             <StringDetect attribute="Reference" context="Reference" String="///" />
  63             <Detect2Chars attribute="Comment" context="Comment" char="/" char1="/"/>
  64             <Detect2Chars attribute="Comment" context="Multi/inline Comment" char="/" char1="*" beginRegion="Comment"/>
  65             <DetectIdentifier/>
  66         </context>
  67         
  68         <context attribute="String" lineEndContext="#pop" name="String">
  69             <DetectIdentifier/>
  70             <HlCStringChar attribute="String Char" context="#stay"/>
  71             <LineContinue attribute="String" context="#stay"/>
  72             <DetectChar attribute="String" context="#pop" char="""/>
  73         </context>
  74         
  75         <context attribute="String Char" lineEndContext="#pop" name="String 1">
  76             <DetectIdentifier/>
  77             <HlCStringChar attribute="String Char" context="#stay"/>
  78             <LineContinue attribute="String" context="#stay"/>
  79             <DetectChar attribute="String Char" context="#pop" char="'"/>
  80         </context>
  81 
  82         <context attribute="Comment" lineEndContext="#pop" name="Comment">
  83             <DetectSpaces />
  84             <IncludeRules context="##Alerts" />
  85             <DetectIdentifier />
  86         </context>
  87         
  88         <context attribute="Comment" lineEndContext="#stay" name="Multi/inline Comment">
  89             <IncludeRules context="##Alerts" />
  90             <Detect2Chars attribute="Comment" context="#pop" char="*" char1="/" endRegion="Comment"/>
  91         </context>
  92         
  93         <context attribute="Reference" lineEndContext="#pop" name="Reference">
  94             <DetectChar attribute="ReferenceBracket" context="#stay" char="<"/>
  95             <DetectChar attribute="ReferenceBracket" context="#stay" char=">"/>
  96             <DetectChar attribute="ReferenceFile" context="ReferenceFile" char="""/>
  97             <DetectChar attribute="ReferenceFile" context="ReferenceFile 1" char="'"/>
  98         </context>
  99         
 100         <context attribute="ReferenceFile" lineEndContext="#pop" name="ReferenceFile">
 101             <DetectIdentifier/>
 102             <HlCStringChar attribute="ReferenceFile" context="#stay"/>
 103             <LineContinue attribute="ReferenceFile" context="#stay"/>
 104             <DetectChar attribute="ReferenceFile" context="#pop" char="""/>
 105         </context>
 106         
 107         <context attribute="ReferenceFile" lineEndContext="#pop" name="ReferenceFile 1">
 108             <DetectIdentifier/>
 109             <HlCStringChar attribute="ReferenceFile" context="#stay"/>
 110             <LineContinue attribute="ReferenceFile" context="#stay"/>
 111             <DetectChar attribute="ReferenceFile" context="#pop" char="'"/>
 112         </context>
 113     </contexts>
 114     <itemDatas>
 115         <itemData name="Normal Text" defStyleNum="dsNormal"/>
 116         <itemData name="Keyword" defStyleNum="dsNormal" color="#00f"/>
 117         <itemData name="Char" defStyleNum="dsChar"/>
 118         <itemData name="String" defStyleNum="dsString" color="#a31515"/>
 119         <itemData name="String Char" defStyleNum="dsString" color="#a31515"/>
 120         <itemData name="Comment" defStyleNum="dsNormal" italic="true" color="#080"/>
 121         <itemData name="Reference" defStyleNum="dsNormal" color="#aeb9ae"/>
 122         <itemData name="ReferenceBracket" defStyleNum="dsNormal" color="#708870" bold="true"/>
 123         <itemData name="ReferenceFile" defStyleNum="dsNormal" color="#2c51cc"/>
 124     </itemDatas>
 125 </highlighting>
 126 <general>
 127     <comments>
 128         <comment name="singleLine" start="//" />
 129         <comment name="multiLine" start="/*" end="*/" />
 130     </comments>
 131     <keywords casesensitive="1"/>
 132 </general>
 133 </language>
Sample code typescript for browser
greeter.html
lib.ts
Any declaration (such as a variable, function, class, type alias, or interface) can be exported by adding the export keyword.
greeter.ts
- import {xyz} from "module";
 
   1 import {getText} from "./lib";
   2 
   3 interface Person {
   4     firstName: string;
   5     lastName: string;
   6 }
   7 
   8 function greeterPerson(p:Person) {
   9     return "Hello GP, " + p.firstName + ' ' + p.lastName + ' ' + getText() ;
  10 }
  11 
  12 function greeter(person:string) {
  13     return "Hello, " + person;
  14 }
  15 
  16 var user = "XPTO User";
  17 
  18 //document.body.innerHTML = greeter(user);
  19 document.body.innerHTML = greeterPerson( 
  20 {firstName:"First",lastName:"Last"}  
  21 );
tsconfig.json
webpack.config.js
build.sh
ReactJS + typescript example
https://reactjs.org/ A Javascript library for building user interfaces. Build encapsulated components that manage their own state, then compose them to make complex UIs.
https://reactjs.org/docs/thinking-in-react.html
Structure
webpack.config.js
tsconfig.json
lib.ts
   1 function getText() {
   2     return "text";
   3 }
   4 
   5 interface Person {
   6     firstName: string;
   7     lastName: string;
   8 }
   9 
  10 function greeterPerson(p: Person) {
  11     return "Hello GP, " + p.firstName + ' ' + p.lastName + ' ' + getText();
  12 }
  13 
  14 function greeter(person: string) {
  15     return "Hello, " + person;
  16 }
  17 
  18 interface HumanInterface {
  19     name: string;
  20     getName(): void;
  21 }
  22 
  23 class Human implements HumanInterface {
  24     name: string;
  25 
  26     constructor(name: string) {
  27         this.name = name;
  28     }
  29 
  30     getName() {
  31         return "My name is " + this.name;
  32     }
  33 }
  34 
  35 class PubSub {
  36     callbacks: Function[];
  37 
  38     constructor() {
  39         this.callbacks = [];
  40     }
  41 
  42     addListener(fn: Function): void {
  43         this.callbacks.push(fn);
  44     }
  45 
  46     notify(message: string): void {
  47         this.callbacks.forEach((fn) => {
  48             fn(message);
  49         });
  50     }
  51 }
  52 let pubSub = new PubSub();
  53 
  54 export { greeter, greeterPerson, Human, HumanInterface, Person, getText, PubSub, pubSub }
greeter.html
package.json
App.tsx
   1 import React, { ReactChild } from 'react';
   2 import { Person, greeterPerson, Human, HumanInterface } from './lib';
   3 import NameHolder from './NameHolder';
   4 import { pubSub } from './lib';
   5 
   6 interface MyState {
   7     currDate: string;
   8     greetings: string;
   9     human: HumanInterface;
  10 }
  11 
  12 function createMyState(currDate: string, greetings: string, human: HumanInterface): MyState {
  13     return { currDate: currDate, greetings: greetings, human: human };
  14 }
  15 
  16 interface MyProps {
  17     prop: string;
  18 }
  19 
  20 export default class App extends React.Component<MyProps, MyState> {
  21     text: string;
  22     timerID: number;
  23 
  24     constructor(props: MyProps) {
  25         super(props);
  26         this.text = this.props.prop;
  27         this.state = createMyState("waiting for date", "waiting for greetings", null); // init with MyState format          
  28     }
  29 
  30     public static createHuman(name: string): HumanInterface {
  31         return new Human(name);
  32     }
  33 
  34     public tickHandler() {
  35         let cd = new Date().toString();
  36         let greetings = greeterPerson({ firstName: "first", lastName: "last" });
  37         let human: HumanInterface = App.createHuman("JohnDoe");
  38         this.setState(createMyState(cd, greetings, human));
  39     }
  40 
  41     componentDidMount() {
  42         // called after the 1st render !
  43         console.log("First render");
  44         this.timerID = setInterval(this.tickHandler.bind(this), 1000);
  45     }
  46 
  47     componentWillUnmount() {
  48         // component will be destroyed
  49         console.log("Will be destroyed soon");
  50         clearInterval(this.timerID);
  51     }
  52 
  53     public render() {
  54         // do not call set state in render !
  55         return (
  56             <div>
  57                 <p>Hello World!!! -- {this.text} -- {this.state.greetings}</p>
  58                 <p>Human {this.state.human != null ? this.state.human.getName() : ""} {this.state.currDate} </p>
  59 
  60                 <p> <NameHolder attr="holding..." />  </p>
  61                 <p> <NameHolder attr={this.state.currDate} /> </p>
  62 
  63                 <div onClick={() => { this.clickHandler(); }} > {this.props.children} </div>
  64             </div>
  65         );
  66     }
  67 
  68     public clickHandler() {
  69         console.log("clicked. # children " + React.Children.count(this.props.children));
  70 
  71         React.Children.forEach(this.props.children, (argx: any) => {
  72 
  73             if (argx.hasOwnProperty("props")) {
  74                 console.log("props property found");
  75                 pubSub.notify("message from outer space !");
  76             }
  77 
  78             console.log(JSON.stringify(argx));
  79         });
  80     }
  81 }
greeter.tsx
   1 import React from 'react';
   2 import ReactDOM from 'react-dom';
   3 import {getText} from "./lib";
   4 import App from './App'; // uses App.tsx
   5 import NameHolder from './NameHolder'; 
   6 
   7 console.log("Entry point");
   8 let appContainer =  document.getElementById('app') ;
   9 let markup = <App prop="Other text inside the page"> <NameHolder attr="NameHolder child inside App "/> </App>;
  10 ReactDOM.render( markup , appContainer);
NameHolder.tsx
   1 import React from 'react';
   2 import { pubSub } from './lib';
   3 
   4 // Component properties (XML attributes)
   5 interface NameHolderProperties {
   6     attr: string;
   7 }
   8 
   9 interface NameHolderState {
  10     attr: string;
  11 }
  12 
  13 // properties and state 
  14 export default class NameHolder extends React.Component<NameHolderProperties, NameHolderState> {
  15     constructor(props: NameHolderProperties) {
  16         super(props); // populates the this.props         
  17         this.state = { attr: this.props.attr };
  18 
  19         pubSub.addListener(this.onMessage);
  20     }
  21 
  22     public render() {
  23         return <span>!!!{this.state.attr}!!!</span>;
  24     }
  25 
  26     public onMessage(message: string): void {
  27         console.log(this.state.attr + " receiVed " + message);
  28     }
  29 }
build.sh
Constants
Console app hello world
   1 cd /tmp
   2 mkdir bar 
   3 cd bar
   4 npm init 
   5 echo '{ "compilerOptions": {  "target": "es5", "sourceMap": true } }' > tsconfig.json 
   6 npm install typescript ts-node
   7 npm install @types/node
   8 echo -e '#!/usr/bin/env node\nconsole.log("Hello world!");' > index.ts
   9 ./node_modules/ts-node/dist/bin.js index.ts
Promise
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise
- The Promise object represents the eventual completion (or failure) of an asynchronous operation and its resulting value.
 
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Using_promises
- A Promise is an object representing the eventual completion or failure of an asynchronous operation.
 
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/all
- The Promise.all() method takes an iterable of promises as an input, and returns a single Promise that resolves to an array of the results of the input promises.
 
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/allSettled
- The Promise.allSettled() method returns a promise that resolves after all of the given promises have either fulfilled or rejected, with an array of objects that each describes the outcome of each promise.
 
index.ts
   1 #!/usr/bin/env node
   2 let p1:Promise<boolean> = new Promise<boolean>(  (resolve,reject)=>{
   3   resolve(true);
   4 } );
   5 p1.then( (value)=>{ 
   6     console.log("resolve sent value " +  value ); 
   7   }
   8 )
   9 let c1:Promise<boolean> = new Promise<boolean>(  (resolve,reject)=>{
  10   reject('Error occurred');
  11 } );
  12 c1.catch( (value)=>{
  13     console.log("reject sent value " + value);
  14   } 
  15 );
  16 console.log("Hello world!");
- ./node_modules/ts-node/dist/bin.js index.ts
 
Hello world! resolve sent value true reject sent value Error occurred
- node_modules/typescript/bin/tsc index.ts
 - node index.js
 
Question mark after interface member name
- It means that the member is optional
 
Exclamation mark after interface member name
- It means that the member is required (not null)
 
Method not implemented
   1   throw new Error("Method not implemented.");
RxJS
https://rxjs.dev/guide/subject
- An RxJS Subject is a special type of Observable that allows values to be multicasted to many Observers.
 
index.ts
   1 #!/usr/bin/env node
   2 import { Observable, Subject, pipe, take, Subscription } from 'rxjs';
   3 
   4 const publisher = new Observable(subscriber => {
   5   subscriber.next(1);
   6   subscriber.next(2);
   7   subscriber.next(3);
   8   setTimeout(() => {
   9     subscriber.next(4);
  10     subscriber.complete();
  11   }, 1000);
  12 });
  13 
  14 console.log("Hello world!");
  15 
  16 publisher.subscribe({
  17   next(x) { console.log('got value ' + x); },
  18   error(err) { console.error('something wrong occurred: ' + err); },
  19   complete() { console.log('done'); }
  20 });
  21 
  22 let eventStream = new Subject();
  23 // only consumes 2 events
  24 let obs1 = eventStream.pipe(take(2))
  25 let subs1: Subscription = obs1.subscribe({
  26   next: (x) => {
  27     console.log('Sub1 next: ' + x);
  28   },
  29   error: (err) => {
  30     console.log('Sub1 error: ' + err);
  31   },
  32   complete: () => {
  33     console.log('Sub1 completed');
  34     console.log(`In complete closed subs1 ${subs1.closed}`);
  35     subs1.unsubscribe();
  36   }
  37 });
  38 
  39 const subscription2: Subscription = eventStream.subscribe({
  40   next: (x) => {
  41     console.log('Sub2 next: ' + x);
  42   },
  43   error: (err) => {
  44     console.log('Sub2 error: ' + err);
  45   },
  46   complete: () => {
  47     console.log('Sub2 completed');
  48   }
  49 });
  50 
  51 // send notifications
  52 setTimeout(() => {
  53   eventStream.next('n1_foo');
  54   eventStream.next('n2_foo');
  55   eventStream.error('e1_foo');
  56   eventStream.error('e2_foo');
  57   eventStream.complete();
  58   console.log(`Closed subs1 ${subs1.closed}`);
  59 }, 3000);
Enums
Using an enum is simple: just access any member as a property off of the enum itself, and declare types using the name of the enum.
https://www.typescriptlang.org/docs/handbook/enums.html#string-enums
https://www.typescriptlang.org/docs/handbook/enums.html#numeric-enums
Microtask
https://developer.mozilla.org/en-US/docs/Web/API/HTML_DOM_API/Microtask_guide
https://developer.mozilla.org/en-US/docs/Web/API/queueMicrotask
Date and epoch
Nullish coalescing operator (??) (double question marks)
The nullish coalescing operator (??) is a logical operator that returns its right-hand side operand when its left-hand side operand is null or undefined, and otherwise returns its left-hand side operand.
