Anwendungsbeispiel

Allgemeine Syntax-Beispiele

 1// TS unterstützt Tupel und optionale parameter
 2type ExampleT = [Number, String, boolean?]
 3
 4const array: ExampleT = [1, "test", true]
 5
 6// TS Generics können mehrere Typen beinhalten
 7const exampleArray: Array<string | Number[]> = []
 8
 9array.push(10)
10array.push("string")
11array.push(false)
12
13// TS unterstützt Fallbacks
14const ex = [] ?? "empty array"
15
16// TS unterstützt Interfaces
17interface ExampleI {
18    propertyOne: boolean
19    propertyTwo: String
20    proptertyThree?: ExampleT
21    propertyFour?: () => void
22}
23
24// TS unterstützt Vererbung
25interface ExampleITwo extends ExampleI {
26    additionnalProperty: Array<String>
27}
28
29// TS unterstützt neben Interfaces auch Typen
30type typeA = {
31    prop1: boolean
32}
33
34type typeB = {
35    prop1: boolean
36}
37
38// TS unterstützt das casten von Typen nach truthy/falsy Prinzip
39const blncast: typeA = {prop1: !![]}
40
41// TS unterstützt das Casten von Typen
42const cast: typeB = blncast as typeB
43
44// TS unterstützt Klassen sowie das Implementieren von Interfaces
45// TS unterstützt Datenkapselung wie private, public, readonly
46// Funktionen und Typen können auch Datentypen in Klassen sein
47class ExampleClass implements ExampleI {
48    constructor(string: String){ this.string = string }
49    private readonly string: string
50
51    propertyOne: boolean = false
52    propertyTwo: String = "string"
53    proptertyThree: ExampleT = [1, "string", true]
54    propertyFour: () => void = () => {}
55
56    public getString() {
57        return this.string
58    }
59}
60
61// erstellen einer Instanz mit Constructorparametern
62const ECC = new ExampleClass("parameter for constructor")
63
64// normale Promise variante via Fetch
65fetch("facebook.com/getUser?id=12345").then(res => console.log(res)).catch(e => console.log(e))
66
67// TS unterstützt import/export syntax
68export type AFType = {
69    url: String
70}
71import { AFTType } from 'example.ts'
72
73// TS empfielt Typisierung von Parametern
74// TS unterstützt async - await um asynchronen Code wie Synchronen zu behandeln
75async function asyncFunction(params: AFType) {
76
77    return await fetch(params.url)
78}
79
80console.log(asyncFunction({url: "facebook.com/getUser?id=12345"}))

Beispielklasse anhand eines Websocket Service

 1// Beispielklasse aus tatsächlich verwendeten Websocket Service
 2import { EMPTY, Subject } from 'rxjs'
 3import { catchError, switchAll, tap } from 'rxjs/operators'
 4import { WebSocketSubject } from 'rxjs/webSocket'
 5import { WebSocketFactory } from 'wsFactory'
 6
 7export class WebsocketService {
 8  private socket$!: WebSocketSubject<string | unknown>
 9
10  private messagesSubject$ = new Subject()
11
12  public messages$ = this.messagesSubject$.pipe(
13    switchAll<unknown | any>(),
14    catchError((e) => {
15      throw e
16    })
17  )
18
19  public connect(path: string): void {
20    if (!this.socket$ || this.socket$.closed) {
21      this.socket$ = WebSocketFactory(WSconfig(path))
22      this.socket$.subscribe()
23      const messages = this.socket$.pipe(
24        tap({
25          error: (error: any) => console.log(error),
26        }),
27        catchError((_) => EMPTY)
28      )
29      this.messagesSubject$.next(messages)
30    }
31  }
32
33  sendMessage(message: string): void {
34    this.socket$.next(JSON.stringify(message))
35  }
36
37  close(): void {
38    this.socket$.unsubscribe()
39    this.socket$.complete()
40  }
41}