MoinMoin Logo
  • Comments
  • Immutable Page
  • Menu
    • Navigation
    • RecentChanges
    • FindPage
    • Local Site Map
    • Help
    • HelpContents
    • HelpOnMoinWikiSyntax
    • Display
    • Attachments
    • Info
    • Raw Text
    • Print View
    • Edit
    • Load
    • Save
  • Login

Navigation

  • Start
  • Sitemap
Revision 41 as of 2020-10-20 22:28:33
  • typescript

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

  • npm install -g typescript

Compile

  • tsc helloworld.ts

kate

https://github.com/PrettyFlower/KateTypeScriptSyntaxHighlighting

wget https://github.com/PrettyFlower/KateTypeScriptSyntaxHighlighting/raw/master/typescript.xml
cp typescript.xml /usr/share/apps/katepart/syntax/typescript.xml

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="&quot;"/>
  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="&quot;"/>
  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="&lt;"/>
  95             <DetectChar attribute="ReferenceBracket" context="#stay" char="&gt;"/>
  96             <DetectChar attribute="ReferenceFile" context="ReferenceFile" char="&quot;"/>
  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="&quot;"/>
 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

   1 npm install -g typescript
   2 npm install -g webpack 

greeter.html

   1 <!DOCTYPE html>
   2 <html>
   3     <head><title>TypeScript Greeter</title><meta charset="UTF-8"></head>
   4     <body>
   5         <script src="dist/bundle.js"></script>
   6     </body>
   7 </html>

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.

export function getText(){
    return "text";
}

greeter.ts

  • import {xyz} from "module";

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

   1 {
   2     "compilerOptions": {
   3         "module": "es6",
   4         "noImplicitAny": true,
   5         "removeComments": true,
   6         "preserveConstEnums": true,
   7         "sourceMap": true
   8     },
   9  "files": [ "greeter.ts",  "lib.ts"] 
  10 }

webpack.config.js

   1 var path = require('path');
   2 
   3 module.exports = {
   4   entry: ['./greeter.js','./lib.js'],
   5   output: {
   6     filename: 'bundle.js',
   7     path: path.resolve(__dirname, 'dist')
   8   }
   9 };

build.sh

   1 tsc
   2 webpack --config webpack.config.js 

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

   1 .
   2 ├── App.tsx
   3 ├── build.sh
   4 ├── greeter.html
   5 ├── greeter.tsx
   6 ├── lib.ts
   7 ├── NameHolder.tsx
   8 ├── package.json
   9 ├── tsconfig.json
  10 └── webpack.config.js

webpack.config.js

   1 var path = require('path');
   2 
   3 module.exports = {
   4   entry: {main:'./greeter.js'},
   5   resolve: { extensions: ['.js', '.jsx', '.ts', '.tsx'] },
   6   output: {
   7     filename: 'bundle.js',
   8     path: path.resolve(__dirname, 'dist')
   9   }
  10 };

tsconfig.json

   1 {
   2     "compilerOptions": {
   3         "module": "es2015",
   4         "target": "es5",
   5         "noImplicitAny": true,
   6         "removeComments": true,
   7         "preserveConstEnums": true,
   8         "sourceMap": true,
   9         "moduleResolution": "node",
  10         "allowSyntheticDefaultImports": true,
  11         "jsx": "react"
  12     }
  13 }

lib.ts

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

   1 <!DOCTYPE html>
   2 <html>
   3     <head><title>React + typescript test</title><meta charset="UTF-8"></head>
   4     <body>        
   5         <div id="app"></div>
   6         <script src="dist/bundle.js"></script>
   7     </body>
   8 </html>

package.json

   1 {
   2   "name": "test",
   3   "private": true,
   4   "version": "0.0.0",
   5   "devDependencies": {
   6     "@types/react": "15.0.35",
   7     "@types/react-dom": "15.5.1",
   8     "@types/webpack-env": "1.13.0",
   9     "react": "15.6.1",
  10     "react-dom": "15.6.1",
  11     "typescript": "2.4.1",
  12     "webpack": "2.5.1"
  13   }
  14 }

App.tsx

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

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

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

   1 PATH=$PATH:./node_modules/typescript/bin
   2 echo Delete dist folder
   3 rm -rf dist
   4 echo Install NPM packages
   5 npm install
   6 echo Compile project
   7 tsc
   8 echo Create application bundle
   9 nodejs ./node_modules/webpack/bin/webpack.js --config webpack.config.js

Constants

export class Constants {
    static readonly CONST_A = "constA";
    static readonly CONST_B = "constB";
}

Console app hello world

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

new Promise<boolean>(  (resolve,reject)=>{
  resolve(true);
  reject('Error occured');
} );

//resolve
.then( (value)=>{} )
// reject
.catch( (value)=>{} )
  • MoinMoin Powered
  • Python Powered
  • GPL licensed
  • Valid HTML 4.01