>
= typescript =
* https://www.typescriptlang.org
* https://www.typescriptlang.org/docs/tutorial.html
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
}}}
== kate ==
[[ https://github.com/PrettyFlower/KateTypeScriptSyntaxHighlighting | KateTypeScriptSyntaxHighlighting]]
{{{#!highlight bash
wget https://github.com/PrettyFlower/KateTypeScriptSyntaxHighlighting/raw/master/typescript.xml
cp typescript.xml /usr/share/apps/katepart/syntax/typescript.xml
}}}
With let keyword added
{{{#!highlight xml
- if
- else
- for
- in
- while
- do
- continue
- break
- with
- try
- catch
- finally
- switch
- case
- new
- var
- function
- return
- delete
- true
- false
- void
- throw
- typeof
- const
- default
- this
- null
- undefined
- class
- export
- declare
- module
- import
- static
- interface
- implements
- constructor
- public
- private
- string
- number
- bool
- any
- extends
- let
}}}
== Sample code typescript for browser ==
{{{#!highlight bash
npm install -g typescript
npm install -g webpack
}}}
=== greeter.html ===
{{{#!highlight html
TypeScript Greeter
}}}
=== lib.ts ===
* [[ https://www.typescriptlang.org/docs/handbook/modules.html | Handbook modules ]]
Any declaration (such as a variable, function, class, type alias, or interface) can be exported by adding the export keyword.
{{{#!highlight javascript
export function getText(){
return "text";
}
}}}
=== greeter.ts ===
* import {xyz} from "module";
{{{#!highlight javascript
import {getText} from "./lib";
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;
}
var user = "XPTO User";
//document.body.innerHTML = greeter(user);
document.body.innerHTML = greeterPerson(
{firstName:"First",lastName:"Last"}
);
}}}
=== tsconfig.json ===
{{{#!highlight javascript
{
"compilerOptions": {
"module": "es6",
"noImplicitAny": true,
"removeComments": true,
"preserveConstEnums": true,
"sourceMap": true
},
"files": [ "greeter.ts", "lib.ts"]
}
}}}
=== webpack.config.js ===
{{{#!highlight javascript
var path = require('path');
module.exports = {
entry: ['./greeter.js','./lib.js'],
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, 'dist')
}
};
}}}
=== build.sh ===
{{{#!highlight bash
tsc
webpack --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 | 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 | 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 | Promises 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 | Promises all settled ]]
* 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 = new Promise( (resolve,reject)=>{
resolve(true);
} );
p1.then( (value)=>{
console.log("resolve sent value " + value );
}
)
let c1:Promise = new Promise( (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
}}}
{{{#!highlight sh
docker pull node:24-alpine
docker run -it node:24-alpine sh
apk add nano
cd /tmp
mkdir foo
cd foo
npm init --init-type=module -y
echo '{ "compilerOptions": { "target": "es2022", "sourceMap": true } }' > tsconfig.json
npm install rxjs
nano index.ts
node index.ts # node v24.21.0 can run ts files directly
}}}
== 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 | string enums ]]
* [[ https://www.typescriptlang.org/docs/handbook/enums.html#numeric-enums | 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 | 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.
{{{#!highlight javascript
const x = null;
const y = x ?? "x is null";
console.log(y);
// "x is null"
}}}
== Docker node24 and typescript ==
=== index.ts ===
{{{#!highlight typescript
#!/usr/bin/env node
interface Acme{
name: string | null | undefined;
}
class Snafu{
private name:string;
constructor(name:string){
this.name = name;
}
getName():string {
return this.name;
}
}
function xyz():Promise{
let r:Acme = {name:"aaa"};
let p1:Promise = new Promise( (resolve,reject)=>{
resolve(r);
});
return p1;
}
function asd():Promise{
let s:Snafu = new Snafu("bbbb");
let p:Promise = new Promise( (resolve,reject)=>{
resolve(s);
});
return p;
}
let promise1 = xyz();
let p2 = asd();
console.log("Hello world!");
promise1.then( (value: Acme)=>{ console.log(value.name); } );
p2.then( (value: Snafu)=>{ console.log(value.getName() ) ; } );
}}}
{{{#!highlight sh
docker pull node:24-alpine
docker run -it node:24-alpine sh
node -v # v24.21.0
npm -v # 11.19.0
cd /tmp
mkdir bar
cd bar
npm init --init-type=module -y
echo '{ "compilerOptions": { "target": "es2022", "sourceMap": true } }' > tsconfig.json
apk add nano
nano index.ts
node index.ts
}}}