diff --git a/05_typescript/uebungen/u04_without-any/index.html b/05_typescript/uebungen/u04_without-any/index.html new file mode 100644 index 0000000..4472844 --- /dev/null +++ b/05_typescript/uebungen/u04_without-any/index.html @@ -0,0 +1,23 @@ + + + + + + Übung 4: Vermeiden von any Parametern in Funktionen + + + + +
+
+
+

Übung 4: Vermeiden von any Parametern in Funktionen

+

+ Refaktoriere eine Funktion, die den Type any für ihre Parameter verwendet. Ersetze any durch spezifischere + Typen, um die Type-Safety zu verbessern. +

+
+
+
+ + diff --git a/05_typescript/uebungen/u04_without-any/package.json b/05_typescript/uebungen/u04_without-any/package.json new file mode 100644 index 0000000..d7f0555 --- /dev/null +++ b/05_typescript/uebungen/u04_without-any/package.json @@ -0,0 +1,16 @@ +{ + "name": "04_without-any", + "version": "1.0.0", + "description": "", + "main": "index.js", + "scripts": { + "ts": "npx esbuild src/main.ts --watch --bundle --outfile=assets/js/bundle.js --loader:.ts=ts" + }, + "keywords": [], + "author": "", + "license": "ISC", + "type": "module", + "devDependencies": { + "esbuild": "^0.28.2" + } +} diff --git a/05_typescript/uebungen/u04_without-any/src/main.ts b/05_typescript/uebungen/u04_without-any/src/main.ts new file mode 100644 index 0000000..4b8567e --- /dev/null +++ b/05_typescript/uebungen/u04_without-any/src/main.ts @@ -0,0 +1,6 @@ +const processData = (input: any): any => { + return input * 2; +}; + +let result = processData('100'); +console.log(result); diff --git a/05_typescript/uebungen/u05_type-annotations/index.html b/05_typescript/uebungen/u05_type-annotations/index.html new file mode 100644 index 0000000..b8a134c --- /dev/null +++ b/05_typescript/uebungen/u05_type-annotations/index.html @@ -0,0 +1,47 @@ + + + + + + Übung 5: Type Annotations in TypeScript-Funktionen + + + + +
+
+
+

Übung 5: Type Annotations in TypeScript-Funktionen

+

+ In dieser Übung übst du das Hinzufügen von Type Annotations zu Variablen und Funktionen in TypeScript. Das + hilft dir dabei, zu verstehen, wie TypeScript Typen herleitet und wann es sinnvoll ist, sie explizit zu + deklarieren. +

+

+ Deine Aufgabe ist es, ein einfaches TypeScript-Programm zu erstellen, das die folgenden Schritte ausführt: +

+
    +
  1. + Deklariere eine Variable, um den Namen einer Person zu speichern, und gib ihn explizit + als String ein. +
  2. +
  3. + Deklariere eine Funktion, die zwei Parameter, firstName und + lastName, beide vom Typ String, benötigt und einen verketteten vollständigen Namen (ebenfalls + vom Typ String) zurückgibt. +
  4. +
  5. + Deklariere eine weitere Funktion, die die Summe des Zahlenfeldes + [10, 20, 30] berechnet. Diese Funktion sollte das Zahlenfeld als Eingabe haben und die Summe + der Zahlen zurückgeben (der Rückgabetyp sollte Zahl sein). +
  6. +
  7. + Verwende die Funktionen und Variablen, um eine Nachricht zu protokollieren, die den vollständigen Namen + einer Person und die Summe einer Reihe von Zahlen enthält. +
  8. +
+
+
+
+ + diff --git a/05_typescript/uebungen/u05_type-annotations/package.json b/05_typescript/uebungen/u05_type-annotations/package.json new file mode 100644 index 0000000..a49183a --- /dev/null +++ b/05_typescript/uebungen/u05_type-annotations/package.json @@ -0,0 +1,16 @@ +{ + "name": "05_type-annotations", + "version": "1.0.0", + "description": "", + "main": "index.js", + "scripts": { + "ts": "npx esbuild src/main.ts --watch --bundle --outfile=assets/js/bundle.js --loader:.ts=ts" + }, + "keywords": [], + "author": "", + "license": "ISC", + "type": "module", + "devDependencies": { + "esbuild": "^0.28.2" + } +} diff --git a/05_typescript/uebungen/u05_type-annotations/src/main.ts b/05_typescript/uebungen/u05_type-annotations/src/main.ts new file mode 100644 index 0000000..b72b5ed --- /dev/null +++ b/05_typescript/uebungen/u05_type-annotations/src/main.ts @@ -0,0 +1,7 @@ +// TODO: Deklariere eine Variable, um den Namen einer Person zu speichern, und gib ihn explizit als String ein. + +// TODO: Deklariere eine Funktion, die zwei Parameter, firstName und lastName, beide vom Typ String, benötigt und einen verketteten vollständigen Namen (ebenfalls vom Typ String) zurückgibt. + +// TODO: Deklariere eine weitere Funktion, die die Summe des Zahlenfeldes [10, 20, 30] berechnet. Diese Funktion sollte das Zahlenfeld als Eingabe haben und die Summe der Zahlen zurückgeben (der Rückgabetyp sollte Zahl sein). + +// TODO: Verwende die Funktionen und Variablen, um eine Nachricht zu protokollieren, die den vollständigen Namen einer Person und die Summe einer Reihe von Zahlen enthält. diff --git a/05_typescript/uebungen/u06_optional-properties/index.html b/05_typescript/uebungen/u06_optional-properties/index.html new file mode 100644 index 0000000..1a4f8bd --- /dev/null +++ b/05_typescript/uebungen/u06_optional-properties/index.html @@ -0,0 +1,58 @@ + + + + + + Übung 6: Definieren und Verwenden von Objekttypen mit optionalen Eigenschaften + + + + +
+
+
+

Übung 6: Definieren und Verwenden von Objekttypen mit optionalen Eigenschaften

+

+ In dieser Übung übst du, Object Types mit erforderlichen und optionalen Eigenschaften in TypeScript zu + definieren. Du erstellst eine Funktion, die mit einem Objekt arbeitet, das ein Buch darstellt. Das Objekt + sollte Eigenschaften für den Titel (ein String), den Autor (ein String) und ein optionales Erscheinungsjahr + (eine Zahl) enthalten. Dann implementierst du eine Logik, um sicher auf diese Eigenschaften zuzugreifen und + sie zu verwenden, einschließlich der optionalen Eigenschaft. +

+
    +
  1. + Definiere einen Objekttyp Book mit den folgenden Eigenschaften: +
      +
    • title: Eine Zeichenkette, die den Titel des Buches angibt.
    • +
    • author: Eine Zeichenkette, die den Autor des Buches angibt.
    • +
    • + yearPublished: Eine optionale Zahl, die das Jahr angibt, in dem das Buch veröffentlicht + wurde. +
    • +
    +
  2. +
  3. + Implementiere eine Funktion printBookDetails, die einen Parameter vom Typ + Book annimmt und die Details des Buches ausgibt. + +
      +
    • + Wenn die yearPublished bereitgestellt wird, drucke sie zusammen mit der title und author + aus. +
    • +
    • + Wenn yearPublished nicht angegeben wird, wird eine Meldung gedruckt, die besagt, dass das + Erscheinungsjahr unbekannt ist. +
    • +
    +
  4. +
  5. + Teste die Funktion mit verschiedenen Objekten, die entweder die Eigenschaft + yearPublished enthalten oder nicht. +
  6. +
+
+
+
+ + diff --git a/05_typescript/uebungen/u06_optional-properties/package.json b/05_typescript/uebungen/u06_optional-properties/package.json new file mode 100644 index 0000000..bf98b04 --- /dev/null +++ b/05_typescript/uebungen/u06_optional-properties/package.json @@ -0,0 +1,13 @@ +{ + "name": "06_optional-properties", + "version": "1.0.0", + "description": "", + "main": "index.js", + "scripts": { + "ts": "npx esbuild src/main.ts --watch --bundle --outfile=assets/js/bundle.js --loader:.ts=ts" + }, + "keywords": [], + "author": "", + "license": "ISC", + "type": "module" +} diff --git a/05_typescript/uebungen/u06_optional-properties/src/main.ts b/05_typescript/uebungen/u06_optional-properties/src/main.ts new file mode 100644 index 0000000..9a8d28a --- /dev/null +++ b/05_typescript/uebungen/u06_optional-properties/src/main.ts @@ -0,0 +1,7 @@ +// Step 1: Define the Book object type + +// Step 2: Implement the function to print book details + +// Test cases to verify your code implementation (comment out the code below to remove the initial errors) +printBookDetails({ title: 'The TypeScript Handbook', author: 'Dan Vanderkam' }); +printBookDetails({ title: 'Clean Code', author: 'Robert C. Martin', yearPublished: 2008 }); diff --git a/05_typescript/uebungen/u07_union-types/index.html b/05_typescript/uebungen/u07_union-types/index.html new file mode 100644 index 0000000..6da4066 --- /dev/null +++ b/05_typescript/uebungen/u07_union-types/index.html @@ -0,0 +1,24 @@ + + + + + + Übung 7: Umgang mit Union Types in TypeScript + + + + +
+
+
+

Übung 7: Umgang mit Union Types in TypeScript

+

+ In dieser Übung übst du den Umgang mit Union Types in TypeScript, indem du eine Funktion erstellst, die + mehrere Typen annimmt und jeden Typ entsprechend behandelt. Du verwendest Techniken fürs Type Narrowing, um + sicherzustellen, dass sich die Funktion je nach Art der Eingabe richtig verhält. +

+
+
+
+ + diff --git a/05_typescript/uebungen/u07_union-types/package.json b/05_typescript/uebungen/u07_union-types/package.json new file mode 100644 index 0000000..c19d3e0 --- /dev/null +++ b/05_typescript/uebungen/u07_union-types/package.json @@ -0,0 +1,13 @@ +{ + "name": "07_union-types", + "version": "1.0.0", + "description": "", + "main": "index.js", + "scripts": { + "ts": "npx esbuild src/main.ts --watch --bundle --outfile=assets/js/bundle.js --loader:.ts=ts" + }, + "keywords": [], + "author": "", + "license": "ISC", + "type": "module" +} diff --git a/05_typescript/uebungen/u07_union-types/src/main.ts b/05_typescript/uebungen/u07_union-types/src/main.ts new file mode 100644 index 0000000..84c25ef --- /dev/null +++ b/05_typescript/uebungen/u07_union-types/src/main.ts @@ -0,0 +1,17 @@ +{ + const processInput = (input: string | number | boolean): string | number => { + // TODO: Implement logic here to handle different types of input + // - If the input is a string, return the string in uppercase + // - If the input is a number, return the square of the number + // - If the input is a boolean, return "Yes" if true, otherwise "No" + + // Placeholder return statement to be replaced + return input; + }; + + // Test cases to verify your code implementation (comment out the code below to remove the initial errors) + console.log(processInput('example')); // => "EXAMPLE" + console.log(processInput(7)); // => 49 + console.log(processInput(true)); // => "Yes" + console.log(processInput(false)); // => "No" +} diff --git a/05_typescript/uebungen/u08_type-aliase/index.html b/05_typescript/uebungen/u08_type-aliase/index.html new file mode 100644 index 0000000..d6ffb95 --- /dev/null +++ b/05_typescript/uebungen/u08_type-aliase/index.html @@ -0,0 +1,24 @@ + + + + + + Übung 8: Type Aliase in TypeScript verwenden + + + + +
+
+
+

Übung 8: Type Aliase in TypeScript verwenden

+

+ In dieser Übung übst du das Erstellen und Verwenden von Type Aliasen, um deinen TypeScript-Code zu + vereinfachen und klarer zu gestalten. Du definierst Type Aliase für einen Objekt- und einen Union Type und + verwendest diese Aliase dann in Funktionen, um deinen Code lesbarer und wartbarer zu machen. +

+
+
+
+ + diff --git a/05_typescript/uebungen/u08_type-aliase/package.json b/05_typescript/uebungen/u08_type-aliase/package.json new file mode 100644 index 0000000..dc6ed54 --- /dev/null +++ b/05_typescript/uebungen/u08_type-aliase/package.json @@ -0,0 +1,13 @@ +{ + "name": "08_type-aliase", + "version": "1.0.0", + "description": "", + "main": "index.js", + "scripts": { + "ts": "npx esbuild src/main.ts --watch --bundle --outfile=assets/js/bundle.js --loader:.ts=ts" + }, + "keywords": [], + "author": "", + "license": "ISC", + "type": "module" +} diff --git a/05_typescript/uebungen/u08_type-aliase/src/main.ts b/05_typescript/uebungen/u08_type-aliase/src/main.ts new file mode 100644 index 0000000..fd40786 --- /dev/null +++ b/05_typescript/uebungen/u08_type-aliase/src/main.ts @@ -0,0 +1,26 @@ +// Step 1: Define a type alias 'Person' for an object type with the following properties: +// - name: a string +// - age: a number +// - isActive: a boolean + +// Step 2: Define a type alias 'ResponseStatus' for a union type that includes the following string literals: +// - "success" +// - "failure" +// - "pending" + +// Step 3: Implement a function 'printPersonDetails' that takes a parameter of type 'Person' +// - The function should print out the person's name, age, and activity status ("Active" or "Inactive" based on the isActive property). + +// Step 4: Implement a function 'handleResponse' that takes a parameter of type 'ResponseStatus' +// - The function should print different messages based on the value of the 'ResponseStatus' ("Operation successful", "Operation failed", "Operation pending"). + +// Test cases to verify your code implementation (comment out the code below to remove the initial errors) + +// Create an object of type 'Person' and pass it to 'printPersonDetails' +const person = { name: 'Alice', age: 30, isActive: true }; +printPersonDetails(person); // => Name: Alice, Age: 30, Status: Active + +// Pass different 'ResponseStatus' values to 'handleResponse' +handleResponse('success'); // => "Operation successful" +handleResponse('failure'); // => "Operation failed" +handleResponse('pending'); // => "Operation pending" diff --git a/05_typescript/uebungen/u09_interfaces/index.html b/05_typescript/uebungen/u09_interfaces/index.html new file mode 100644 index 0000000..4b8003b --- /dev/null +++ b/05_typescript/uebungen/u09_interfaces/index.html @@ -0,0 +1,25 @@ + + + + + + Übung 9: Implementieren und Erweitern von Interfaces in TypeScript + + + + +
+
+
+

Übung 9: Implementieren und Erweitern von Interfaces in TypeScript

+

+ In dieser Übung übst du das Erstellen und Verwenden von Interfaces in TypeScript. Du definierst Interfaces, + um die Struktur von Objekten zu beschreiben, und erweiterst diese Interfaces dann, um zusätzliche + Eigenschaften hinzuzufügen. Außerdem lernst du das Konzept der declaration merging kennen, indem du neue + Felder zu einem bestehenden Interface hinzufügst. +

+
+
+
+ + diff --git a/05_typescript/uebungen/u09_interfaces/package.json b/05_typescript/uebungen/u09_interfaces/package.json new file mode 100644 index 0000000..edefa08 --- /dev/null +++ b/05_typescript/uebungen/u09_interfaces/package.json @@ -0,0 +1,13 @@ +{ + "name": "09_interfaces", + "version": "1.0.0", + "description": "", + "main": "index.js", + "scripts": { + "ts": "npx esbuild src/main.ts --watch --bundle --outfile=assets/js/bundle.js --loader:.ts=ts" + }, + "keywords": [], + "author": "", + "license": "ISC", + "type": "module" +} diff --git a/05_typescript/uebungen/u09_interfaces/src/main.ts b/05_typescript/uebungen/u09_interfaces/src/main.ts new file mode 100644 index 0000000..9bb1fbf --- /dev/null +++ b/05_typescript/uebungen/u09_interfaces/src/main.ts @@ -0,0 +1,27 @@ +// Step 1: Define an interface 'Person' with the following properties: +// - name: a string +// - age: a number + +// Step 2: Extend the 'Person' interface to create an 'Employee' interface with an additional property: +// - employeeId: a number + +// Step 3: Implement a function 'printEmployeeDetails' that takes a parameter of type 'Employee' +// - The function should print out the employee's name, age, and employeeId. + +// Step 4: Declare the 'Display' interface with a property: +// - resolution: a string + +// Step 5: Add a new property 'size: number' to the 'Display' interface using declaration merging + +// Step 6: Implement a function 'printDisplayDetails' that takes a parameter of type 'Display' +// - The function should print out the display's resolution and size. + +// Test cases to verify your code implementation (comment out the code below to remove the initial errors) + +// Create an 'Employee' object and pass it to 'printEmployeeDetails' +const employee = { name: 'Bob', age: 40, employeeId: 12345 }; +printEmployeeDetails(employee); // => Name: Bob, Age: 40, Employee ID: 12345 + +// Create a 'Display' object and pass it to 'printDisplayDetails' +const display = { resolution: '4K', size: 27 }; +printDisplayDetails(display); // => Resolution: 4K, Size: 27 diff --git a/05_typescript/uebungen/u10_assertions/index.html b/05_typescript/uebungen/u10_assertions/index.html new file mode 100644 index 0000000..435e437 --- /dev/null +++ b/05_typescript/uebungen/u10_assertions/index.html @@ -0,0 +1,48 @@ + + + + + + Übung 10: Type Assertions in TypeScript anwenden + + + + +
+
+
+

Übung 10: Type Assertions in TypeScript anwenden

+

+ In dieser Übung verwendest du Type Assertions, um mit unbekannten Typen zu arbeiten und ein Objekt in einen + benutzerdefinierten Typ zu casten. +

+

Anweisungen

+
    +
  • Erstelle ein Objekt mysteryObject mit einer Eigenschaft info, die eine Zeichenkette enthält.
  • + +
  • Das Objekt sollte vom Typ unknown sein.
  • + +
  • Verwende eine Type Assertion, um zu behaupten, dass mysteryObject vom Typ { info: string } ist.
  • + +
  • + Greife auf die Info-Eigenschaft von mysteryObject zu und ändere ihren Wert in eine neue Zeichenkette. +
  • +
  • Definiere einen eigenen Typ ComplexObject mit einer Methode compute, die einen String zurückgibt.
  • + +
  • + Erstelle ein Objekt basicObject mit einer Methode compute. +
      +
    • Die Methode sollte die Zeichenfolge "Basic Computation" zurückgeben.
    • +
    +
  • +
  • + Verwende eine zweistufige Type Assertion, um zu behaupten, dass basicObject vom Typ ComplexObject ist. +
  • + +
  • Rufe die Berechnungsmethode auf basicObject auf und protokolliere das Ergebnis.
  • +
+
+
+
+ + diff --git a/05_typescript/uebungen/u10_assertions/package.json b/05_typescript/uebungen/u10_assertions/package.json new file mode 100644 index 0000000..d294086 --- /dev/null +++ b/05_typescript/uebungen/u10_assertions/package.json @@ -0,0 +1,13 @@ +{ + "name": "10_assertions", + "version": "1.0.0", + "description": "", + "main": "index.js", + "scripts": { + "ts": "npx esbuild src/main.ts --watch --bundle --outfile=assets/js/bundle.js --loader:.ts=ts" + }, + "keywords": [], + "author": "", + "license": "ISC", + "type": "module" +} diff --git a/05_typescript/uebungen/u10_assertions/src/main.ts b/05_typescript/uebungen/u10_assertions/src/main.ts new file mode 100644 index 0000000..3a52c34 --- /dev/null +++ b/05_typescript/uebungen/u10_assertions/src/main.ts @@ -0,0 +1,34 @@ +// [ ] Step 1: Create an object 'mysteryObject' with a property 'info' that holds a string. +// - The object should be of type 'unknown'. + +// [ ] Step 2: Use a type assertion to assert that 'mysteryObject' is of type '{ info: string }'. + +// [ ] Step 3: Access the 'info' property and assign a new string to it. + +// [ ] Step 4: Define a custom type 'ComplexObject' with a method 'compute' that returns a string. + +// [ ] Step 5: Create an object 'basicObject' with a method 'compute'. +// - The method should return a string "Basic Computation". + +// [ ] Step 6: Use a two-step type assertion to assert that 'basicObject' is of type 'ComplexObject'. + +// [ ] Step 7: Call the 'compute' method on 'basicObject' and log the result. + +// Test cases to verify your code implementation (comment out the code below to remove the initial errors) + +// Verify that 'info' was correctly accessed and modified +console.log('Updated info:', typedMysteryObject.info); // => "Updated Info" + +// Verify that 'compute' method of 'complexObject' returns the expected result +if (complexObject.compute() === 'Basic Computation') { + console.log('compute method returned the expected result.'); +} else { + console.error('compute method did not return the expected result.'); +} + +// Verify 'info' type compatibility +if (typeof typedMysteryObject.info === 'string') { + console.log('info property is of type string.'); +} else { + console.error('info property is not of type string.'); +} diff --git a/05_typescript/uebungen/uebungen-04-10-ts.zip b/05_typescript/uebungen/uebungen-04-10-ts.zip new file mode 100644 index 0000000..a4a7de5 Binary files /dev/null and b/05_typescript/uebungen/uebungen-04-10-ts.zip differ diff --git a/05_typescript/unterricht/tag29/01_ts-types/assets/js/05_type-statement.js b/05_typescript/unterricht/tag29/01_ts-types/assets/js/05_type-statement.js index 8afef30..4150a6a 100644 --- a/05_typescript/unterricht/tag29/01_ts-types/assets/js/05_type-statement.js +++ b/05_typescript/unterricht/tag29/01_ts-types/assets/js/05_type-statement.js @@ -1,2 +1,34 @@ (() => { + // src/05_type-statement.ts + { + let capitalize = function(input) { + return input.charAt(0).toUpperCase() + input.slice(1); + }, applyTransform = function(input, transform) { + return transform(input); + }; + const printCarDetails = (car) => { + console.log(`Car Make: ${car.make}`); + console.log(`Car Model: ${car.model}`); + console.log(`Car Year: ${car.year}`); + }; + const myCar = { make: "Toyota", model: "Corolla", year: 2021 }; + printCarDetails(myCar); + const displayStatus = (status) => { + if (status === "success") { + console.log("Operation was successful!"); + } else if (status === "error") { + console.log("There was an error."); + } else { + console.log("Loading..."); + } + }; + displayStatus("success"); + displayStatus("error"); + displayStatus("loading"); + console.log(applyTransform("hello", capitalize)); + const greetName = (name) => { + return `Hello, ${name}`; + }; + console.log(greetName("Philippe")); + } })(); diff --git a/05_typescript/unterricht/tag29/01_ts-types/assets/js/06_interface-extends.js b/05_typescript/unterricht/tag29/01_ts-types/assets/js/06_interface-extends.js new file mode 100644 index 0000000..a65126f --- /dev/null +++ b/05_typescript/unterricht/tag29/01_ts-types/assets/js/06_interface-extends.js @@ -0,0 +1,39 @@ +(() => { + // src/06_interface-extends.ts + { + const printVehicleInfo = (vehicle) => { + console.log(`Make: ${vehicle.make}`); + console.log(`Model: ${vehicle.model}`); + console.log(`Year: ${vehicle.year}`); + }; + printVehicleInfo({ make: "Honda", model: "Civic", year: 2020 }); + const employee = { + name: "John Doe", + age: 30, + employeeId: 123 + }; + console.log(employee.name); + console.log(employee.age); + console.log(employee.employeeId); + } + { + const employee = { + name: "John Doe", + age: 30, + employeeId: 12345 + }; + console.log(employee.name); + console.log(employee.age); + console.log(employee.employeeId); + } + { + const monitor = { + resolution: "1080p", + size: 24 + }; + console.log(monitor.resolution); + console.log(monitor.size); + } + { + } +})(); diff --git a/05_typescript/unterricht/tag29/01_ts-types/assets/js/07_type-as-statement.js b/05_typescript/unterricht/tag29/01_ts-types/assets/js/07_type-as-statement.js new file mode 100644 index 0000000..8a3557e --- /dev/null +++ b/05_typescript/unterricht/tag29/01_ts-types/assets/js/07_type-as-statement.js @@ -0,0 +1,12 @@ +(() => { + // src/07_type-as-statement.ts + { + const h1El = document.querySelector("h1"); + const headlineEl = document.querySelector("h1"); + headlineEl.style.color = "tomato"; + const pEl = document.querySelector("p"); + const paragraphEl = document.querySelector("p"); + console.log({ width: pEl?.offsetWidth, height: pEl?.offsetHeight }); + console.log({ width: paragraphEl.offsetWidth, height: paragraphEl.offsetHeight }); + } +})(); diff --git a/05_typescript/unterricht/tag29/01_ts-types/index.html b/05_typescript/unterricht/tag29/01_ts-types/index.html index 77854f0..bccbe85 100644 --- a/05_typescript/unterricht/tag29/01_ts-types/index.html +++ b/05_typescript/unterricht/tag29/01_ts-types/index.html @@ -7,9 +7,12 @@ - - - + + + + + +
diff --git a/05_typescript/unterricht/tag29/01_ts-types/src/05_type-statement.ts b/05_typescript/unterricht/tag29/01_ts-types/src/05_type-statement.ts index e69de29..e5cf00a 100644 --- a/05_typescript/unterricht/tag29/01_ts-types/src/05_type-statement.ts +++ b/05_typescript/unterricht/tag29/01_ts-types/src/05_type-statement.ts @@ -0,0 +1,69 @@ +// type statement - eigene Datentyp-Annotationen definieren +{ + // interface für wachsende und komplexe Datenstrukturen. Meistens (global) ausgelagert. + + // interface Car { + // make: string; + // model: string; + // year: number; + // } + + // type aliases innerhalb von Dokumenten für einfache, festehende type und unios + + type Car = { + make: string; + model: string; + year: number; + }; + + const printCarDetails = (car: Car) => { + console.log(`Car Make: ${car.make}`); + console.log(`Car Model: ${car.model}`); + console.log(`Car Year: ${car.year}`); + }; + + const myCar = { make: 'Toyota', model: 'Corolla', year: 2021 }; + printCarDetails(myCar); + + // ======= + + type Status = 'success' | 'error' | 'loading'; + + const displayStatus = (status: Status) => { + if (status === 'success') { + console.log('Operation was successful!'); + } else if (status === 'error') { + console.log('There was an error.'); + } else { + console.log('Loading...'); + } + }; + + displayStatus('success'); // OK + displayStatus('error'); // OK + displayStatus('loading'); // OK + + // displayStatus('Loading'); // Error: Argument of type '"Loading"' is not assignable to parameter of type 'Status'. + // displayStatus('complete'); // Error: Argument of type '"complete"' is not assignable to parameter of type 'Status'. + + // ========= + // type für Funktion als parameter oder Funktionsausdrücke + + type StringFn = (param: string) => string; + + function capitalize(input: string): string { + return input.charAt(0).toUpperCase() + input.slice(1); + } + + function applyTransform(input: string, transform: StringFn): string { + return transform(input); + } + + console.log(applyTransform('hello', capitalize)); // => "Hello" + + const greetName: StringFn = (name) => { + return `Hello, ${name}`; + }; + + console.log(greetName('Philippe')); +} diff --git a/05_typescript/unterricht/tag29/01_ts-types/src/06_interface-extends.ts b/05_typescript/unterricht/tag29/01_ts-types/src/06_interface-extends.ts new file mode 100644 index 0000000..b58ccbf --- /dev/null +++ b/05_typescript/unterricht/tag29/01_ts-types/src/06_interface-extends.ts @@ -0,0 +1,91 @@ +// Interfaces - eine leistungsstarke Funktion zur Definition der Form eines Objekts. Ein Interface ermöglicht es dir, die Eigenschaften, die ein Objekt haben soll, zusammen mit ihren Typen festzulegen, was deinen Code lesbarer und einfacher zu pflegen macht. +{ + interface Vehicle { + make: string; + model: string; + year: number; + } + + const printVehicleInfo = (vehicle: Vehicle) => { + console.log(`Make: ${vehicle.make}`); + console.log(`Model: ${vehicle.model}`); + console.log(`Year: ${vehicle.year}`); + }; + + printVehicleInfo({ make: 'Honda', model: 'Civic', year: 2020 }); + // Object literal may only specify known properties, and 'releaseYear' does not exist in type 'Vehicle'. + // printVehicleInfo({ make: 'Nissan', model: 'Pao', releaseYear: 1984 }); + + // ----- + + interface Person { + name: string; + age: number; + } + + interface Employee extends Person { + employeeId: number; + } + + const employee: Employee = { + name: 'John Doe', + age: 30, + employeeId: 123, + }; + + console.log(employee.name); // from Person + console.log(employee.age); // from Person + console.log(employee.employeeId); // from Employee +} +// ------ +{ + type Person = { + name: string; + age: number; + }; + + // NOT RECOMMENDED - use interfaces instead + // Erweiterung bei type Objekt mit "&" ampersand + type Employee = Person & { + employeeId: number; + }; + + const employee: Employee = { + name: 'John Doe', + age: 30, + employeeId: 12345, + }; + + console.log(employee.name); + console.log(employee.age); + console.log(employee.employeeId); +} +//---- +{ + interface Display { + resolution: string; + } + + interface Display { + size: number; + } + + const monitor: Display = { + resolution: '1080p', + size: 24, + }; + + console.log(monitor.resolution); // => 1080p + console.log(monitor.size); // => 24 +} +//------ +{ + type Display = { + resolution: string; + }; + + // type Display = { + // size: number; + // }; + // Error: Duplicate identifier 'Display'. +} diff --git a/05_typescript/unterricht/tag29/01_ts-types/src/07_type-as-statement.ts b/05_typescript/unterricht/tag29/01_ts-types/src/07_type-as-statement.ts new file mode 100644 index 0000000..fab9ad7 --- /dev/null +++ b/05_typescript/unterricht/tag29/01_ts-types/src/07_type-as-statement.ts @@ -0,0 +1,18 @@ +// Type Assertions verwenden - mit "as" statement festen Datentyp zuweisen +{ + const h1El: HTMLHeadingElement | null = document.querySelector('h1'); + + // selber festgelegt + const headlineEl = document.querySelector('h1') as HTMLHeadingElement; + + // h1El?.style?.color = 'tomato'; + headlineEl.style.color = 'tomato'; + + const pEl: HTMLParagraphElement | null = document.querySelector('p'); + + // selber festgelegt + const paragraphEl = document.querySelector('p'); + + console.log({ width: pEl?.offsetWidth, height: pEl?.offsetHeight }); + console.log({ width: paragraphEl.offsetWidth, height: paragraphEl.offsetHeight }); +}