diff --git a/04_typescript/agenda.md b/04_typescript/agenda.md
index edaef5c..4f10f06 100644
--- a/04_typescript/agenda.md
+++ b/04_typescript/agenda.md
@@ -510,3 +510,32 @@ Projekte + weiteres Modul einbinden
**Übungen:**
Übungen 10 - 18
+
+---
+
+### Tag 34
+
+**Inhalt:**
+
+- TS Funktionen und Objekte
+- Abschluss TypeScript Grundlagen
+- Abschlussquiz
+
+**Übungen:**
+
+Übungen 19 - 31
+Projektarbeit
+
+---
+
+### Tag 35
+
+**Inhalt:**
+
+- Projekt-Webseite in TS
+- Optimierung mit KI
+- 1:1 Meeting
+
+**Übungen:**
+
+Projektarbeit
diff --git a/04_typescript/uebungen/11_literals/assets/js/bundle.js b/04_typescript/uebungen/11_literals/assets/js/bundle.js
new file mode 100644
index 0000000..ef7a6ec
--- /dev/null
+++ b/04_typescript/uebungen/11_literals/assets/js/bundle.js
@@ -0,0 +1,34 @@
+(() => {
+ var __getOwnPropNames = Object.getOwnPropertyNames;
+ var __commonJS = (cb, mod) => function __require() {
+ try {
+ return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
+ } catch (e) {
+ throw mod = 0, e;
+ }
+ };
+
+ // src/main.ts
+ var require_main = __commonJS({
+ "src/main.ts"() {
+ {
+ const setStatus = (status) => {
+ console.log(status);
+ };
+ const rateExperience = (rating) => {
+ return `You rated the experience as ${rating}`;
+ };
+ const togglePower = (state) => {
+ return state ? "Power is on" : "Power is off";
+ };
+ setStatus("success");
+ setStatus("error");
+ console.log(rateExperience(5));
+ console.log(rateExperience(3));
+ console.log(togglePower(true));
+ console.log(togglePower(false));
+ }
+ }
+ });
+ require_main();
+})();
diff --git a/04_typescript/uebungen/11_literals/src/main.ts b/04_typescript/uebungen/11_literals/src/main.ts
index 468d4b5..7d5a4f8 100644
--- a/04_typescript/uebungen/11_literals/src/main.ts
+++ b/04_typescript/uebungen/11_literals/src/main.ts
@@ -1,30 +1,45 @@
-// [ ] Step 1: Create a function 'setStatus' that accepts a string literal type parameter 'status'.
-// - The 'status' can only be "success", "error", or "loading".
-// - The function should log the status to the console.
+{
+ // [x] Step 1: Create a function 'setStatus' that accepts a string literal type parameter 'status'.
+ // - The 'status' can only be "success", "error", or "loading".
+ // - The function should log the status to the console.
-// [ ] Step 2: Create a function 'rateExperience' that accepts a numeric literal type parameter 'rating'.
-// - The 'rating' can only be 1, 2, 3, 4, or 5.
-// - The function should return a message indicating the rating.
+ const setStatus = (status: 'success' | 'error' | 'loading'): void => {
+ console.log(status);
+ };
-// [ ] Step 3: Create a function 'togglePower' that accepts a boolean literal type parameter 'state'.
-// - The 'state' can only be true or false.
-// - The function should return a message indicating whether the power is ON or OFF.
+ // [x] Step 2: Create a function 'rateExperience' that accepts a numeric literal type parameter 'rating'.
+ // - The 'rating' can only be 1, 2, 3, 4, or 5.
+ // - The function should return a message indicating the rating.
+ type Rating = 1 | 2 | 3 | 4 | 5;
-// [ ] Step 4: Test the functions with valid and invalid values to ensure the correct behavior and type safety.
+ const rateExperience = (rating: Rating): string => {
+ return `You rated the experience as ${rating}`;
+ };
-// Test cases (students should verify that these work as expected)
+ // [x] Step 3: Create a function 'togglePower' that accepts a boolean literal type parameter 'state'.
+ // - The 'state' can only be true or false.
+ // - The function should return a message indicating whether the power is ON or OFF.
-// Test 'setStatus' function
-setStatus('success'); // OK
-setStatus('error'); // OK
-setStatus('complete'); // Error: Argument of type '"complete"' is not assignable to parameter of type '"success" | "error" | "loading"'.
+ const togglePower = (state: boolean) => {
+ return state ? 'Power is on' : 'Power is off';
+ };
-// Test 'rateExperience' function
-console.log(rateExperience(5)); // => "You rated the experience as 5"
-console.log(rateExperience(3)); // => "You rated the experience as 3"
-console.log(rateExperience(6)); // Error: Argument of type '6' is not assignable to parameter of type '1 | 2 | 3 | 4 | 5'.
+ // [x] Step 4: Test the functions with valid and invalid values to ensure the correct behavior and type safety.
-// Test 'togglePower' function
-console.log(togglePower(true)); // => "Power is ON"
-console.log(togglePower(false)); // => "Power is OFF"
-console.log(togglePower('on')); // Error: Argument of type '"on"' is not assignable to parameter of type 'true | false'.
+ // Test cases (students should verify that these work as expected)
+
+ // Test 'setStatus' function
+ setStatus('success'); // OK
+ setStatus('error'); // OK
+ //setStatus('complete'); // Error: Argument of type '"complete"' is not assignable to parameter of type '"success" | "error" | "loading"'.
+
+ // Test 'rateExperience' function
+ console.log(rateExperience(5)); // => "You rated the experience as 5"
+ console.log(rateExperience(3)); // => "You rated the experience as 3"
+ //console.log(rateExperience(6)); // Error: Argument of type '6' is not assignable to parameter of type '1 | 2 | 3 | 4 | 5'.
+
+ // Test 'togglePower' function
+ console.log(togglePower(true)); // => "Power is ON"
+ console.log(togglePower(false)); // => "Power is OFF"
+ //console.log(togglePower('on')); // Error: Argument of type '"on"' is not assignable to parameter of type 'true | false'.
+}
diff --git a/04_typescript/uebungen/12_type-guard/assets/js/bundle.js b/04_typescript/uebungen/12_type-guard/assets/js/bundle.js
new file mode 100644
index 0000000..2662f2c
--- /dev/null
+++ b/04_typescript/uebungen/12_type-guard/assets/js/bundle.js
@@ -0,0 +1,35 @@
+(() => {
+ var __getOwnPropNames = Object.getOwnPropertyNames;
+ var __commonJS = (cb, mod) => function __require() {
+ try {
+ return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
+ } catch (e) {
+ throw mod = 0, e;
+ }
+ };
+
+ // src/main.ts
+ var require_main = __commonJS({
+ "src/main.ts"() {
+ {
+ const formatInput = (input) => {
+ switch (typeof input) {
+ case "number":
+ return String(input * 100);
+ case "string":
+ return input.toLowerCase();
+ case "boolean":
+ return input ? "Yes" : "No";
+ }
+ };
+ console.log(formatInput(0.5));
+ console.log(formatInput(12));
+ console.log(formatInput("Hello"));
+ console.log(formatInput("WORLD"));
+ console.log(formatInput(true));
+ console.log(formatInput(false));
+ }
+ }
+ });
+ require_main();
+})();
diff --git a/04_typescript/uebungen/12_type-guard/src/main.ts b/04_typescript/uebungen/12_type-guard/src/main.ts
index 328b727..85f5676 100644
--- a/04_typescript/uebungen/12_type-guard/src/main.ts
+++ b/04_typescript/uebungen/12_type-guard/src/main.ts
@@ -1,19 +1,34 @@
-console.log(formatInput(0.5)); // => "50"
-console.log(formatInput(12)); // => "1200"
-console.log(formatInput('Hello')); // => "hello"
-console.log(formatInput('WORLD')); // => "world"
-console.log(formatInput(true)); // => "Yes"
-console.log(formatInput(false)); // => "No"
+{
+ // Übung 12: Implementiere eine Type Guard Funktion
+ // Schreibe eine TypeScript-Funktion namens formatInput, die einen Parameter input akzeptiert, der vom Typ number, string oder boolean sein kann. Die Funktion sollte einen formatierten String zurückgeben, der auf dem Typ der Eingabe basiert:
+ const formatInput = (input: number | string | boolean): string => {
+ switch (typeof input) {
+ case 'number':
+ return String(input * 100);
+ case 'string':
+ return input.toLowerCase();
+ case 'boolean':
+ return input ? 'Yes' : 'No';
+ default:
+ console.error('No provided type');
-// Übung 12: Implementiere eine Type Guard Funktion
-// Schreibe eine TypeScript-Funktion namens formatInput, die einen Parameter input akzeptiert, der vom Typ number, string oder boolean sein kann. Die Funktion sollte einen formatierten String zurückgeben, der auf dem Typ der Eingabe basiert:
+ return '';
+ }
+ };
-// Wenn input eine number ist, gibst du die Zahl multipliziert mit 100 als string zurück.
+ // [x] Wenn input eine number ist, gibst du die Zahl multipliziert mit 100 als string zurück.
-// Wenn input ein string ist, wird string in Kleinbuchstaben zurückgegeben.
+ // [x] Wenn input ein string ist, wird string in Kleinbuchstaben zurückgegeben.
-// Wenn input eine boolean ist, gib "Yes" zurück, wenn input eine true ist, und "No", wenn input eine false ist.
+ // [x] Wenn input eine boolean ist, gib "Yes" zurück, wenn input eine true ist, und "No", wenn input eine false ist.
-// Verwende den typeof Operator, um die Typen innerhalb der Funktion einzugrenzen.
+ // Verwende den typeof Operator, um die Typen innerhalb der Funktion einzugrenzen.
+ // Kopiere den Code unten und füge ihn ein, um deine Implementierung zu testen.
-// Kopiere den Code unten und füge ihn ein, um deine Implementierung zu testen.
+ console.log(formatInput(0.5)); // => "50"
+ console.log(formatInput(12)); // => "1200"
+ console.log(formatInput('Hello')); // => "hello"
+ console.log(formatInput('WORLD')); // => "world"
+ console.log(formatInput(true)); // => "Yes"
+ console.log(formatInput(false)); // => "No"
+}
diff --git a/04_typescript/uebungen/13_narrowing/assets/js/bundle.js b/04_typescript/uebungen/13_narrowing/assets/js/bundle.js
new file mode 100644
index 0000000..542dc95
--- /dev/null
+++ b/04_typescript/uebungen/13_narrowing/assets/js/bundle.js
@@ -0,0 +1,33 @@
+(() => {
+ var __getOwnPropNames = Object.getOwnPropertyNames;
+ var __commonJS = (cb, mod) => function __require() {
+ try {
+ return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
+ } catch (e) {
+ throw mod = 0, e;
+ }
+ };
+
+ // src/main.ts
+ var require_main = __commonJS({
+ "src/main.ts"() {
+ {
+ const displayStatus = (status2) => {
+ if (status2) {
+ return `Status: ${status2}`;
+ } else {
+ return "No status avaible";
+ }
+ };
+ let status;
+ console.log(displayStatus("Active"));
+ console.log(displayStatus("Pending"));
+ console.log(displayStatus(null));
+ console.log(displayStatus(void 0));
+ console.log(displayStatus(status));
+ console.log(displayStatus(""));
+ }
+ }
+ });
+ require_main();
+})();
diff --git a/04_typescript/uebungen/13_narrowing/src/main.ts b/04_typescript/uebungen/13_narrowing/src/main.ts
index 4b961fb..c44de65 100644
--- a/04_typescript/uebungen/13_narrowing/src/main.ts
+++ b/04_typescript/uebungen/13_narrowing/src/main.ts
@@ -1,17 +1,31 @@
-console.log(displayStatus('Active')); // => "Status: Active"
-console.log(displayStatus('Pending')); // => "Status: Pending"
-console.log(displayStatus(null)); // => "No status available."
-console.log(displayStatus(undefined)); // => "No status available."
-console.log(displayStatus('')); // => "No status available."
+{
+ // Übung 13: Implementierung der Truthiness Narrowing in einer Funktion
+ // Schreibe eine TypeScript-Funktion namens displayStatus, die einen Parameter status akzeptiert, der ein string, null oder undefined sein kann. Die Funktion sollte:
-// Übung 13: Implementierung der Truthiness Narrowing in einer Funktion
-// Schreibe eine TypeScript-Funktion namens displayStatus, die einen Parameter status akzeptiert, der ein string, null oder undefined sein kann. Die Funktion sollte:
+ const displayStatus = (status: string | null | undefined): string => {
+ if (status) {
+ return `Status: ${status}`;
+ } else {
+ return 'No status avaible';
+ }
+ };
-// Wenn status truthy ist, wird die Zeichenfolge "Status: ", verkettet mit Status.
+ // [x] Wenn status truthy ist, wird die Zeichenfolge "Status: ", verkettet mit Status.
-// Wenn status fehlerhaft ist, wird die Zeichenfolge "No status available." zurückgegeben.
+ // [x] Wenn status fehlerhaft ist, wird die Zeichenfolge "No status available." zurückgegeben.
-// Verwende die Truthiness Narrowing, um zu prüfen, ob der Status truthy oder falsch ist.
+ // [x] Verwende die Truthiness Narrowing, um zu prüfen, ob der Status truthy oder falsch ist.
-// Kopiere den Code unten und füge ihn ein, um deine Implementierung zu testen.
-// // Kopiere den Code unten und füge ihn ein, um deine Implementierung zu testen.
+ // [x] Kopiere den Code unten und füge ihn ein, um deine Implementierung zu testen.
+ // [x] Kopiere den Code unten und füge ihn ein, um deine Implementierung zu testen.
+
+ let status;
+
+ console.log(displayStatus('Active')); // => "Status: Active"
+ console.log(displayStatus('Pending')); // => "Status: Pending"
+ console.log(displayStatus(null)); // => "No status available."
+ console.log(displayStatus(undefined)); // => "No status available."
+ console.log(displayStatus(status)); // => "No status available."
+ console.log(displayStatus('')); // => "No status available."
+ // console.log(displayStatus()); // => Expected 1 arguments, but got 0.
+}
diff --git a/04_typescript/uebungen/14_narrowing-equality/assets/js/bundle.js b/04_typescript/uebungen/14_narrowing-equality/assets/js/bundle.js
new file mode 100644
index 0000000..573a040
--- /dev/null
+++ b/04_typescript/uebungen/14_narrowing-equality/assets/js/bundle.js
@@ -0,0 +1,52 @@
+(() => {
+ var __getOwnPropNames = Object.getOwnPropertyNames;
+ var __commonJS = (cb, mod) => function __require() {
+ try {
+ return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
+ } catch (e) {
+ throw mod = 0, e;
+ }
+ };
+
+ // src/main.ts
+ var require_main = __commonJS({
+ "src/main.ts"() {
+ {
+ const analyzeInput = (input) => {
+ switch (typeof input) {
+ case "boolean":
+ return input ? "Input is exactly true" : "Input is exactly false";
+ case "number":
+ if (input === 0) {
+ return "Input is zero";
+ } else if (input > 0) {
+ return "Input is a positive number";
+ } else {
+ return "Input is a negative number";
+ }
+ case "string":
+ if (input === "hello") {
+ return `Input is the string '${input}'`;
+ } else {
+ return "Input is another string";
+ }
+ default:
+ return "Unknown input";
+ }
+ };
+ console.log("undefined", "object");
+ console.log(analyzeInput(true));
+ console.log(analyzeInput(false));
+ console.log(analyzeInput(0));
+ console.log(analyzeInput(42));
+ console.log(analyzeInput(-7));
+ console.log(analyzeInput("hello"));
+ console.log(analyzeInput("world"));
+ console.log(analyzeInput(""));
+ console.log(analyzeInput(void 0));
+ console.log(analyzeInput(null));
+ }
+ }
+ });
+ require_main();
+})();
diff --git a/04_typescript/uebungen/14_narrowing-equality/src/main.ts b/04_typescript/uebungen/14_narrowing-equality/src/main.ts
index caeee4d..6c8607f 100644
--- a/04_typescript/uebungen/14_narrowing-equality/src/main.ts
+++ b/04_typescript/uebungen/14_narrowing-equality/src/main.ts
@@ -1,35 +1,51 @@
-const analyzeInput = (input: string | number | boolean): string => {
- // Your code here
-};
+{
+ const analyzeInput = (input: string | number | boolean | undefined | null): string => {
+ switch (typeof input) {
+ case 'boolean':
+ return input ? 'Input is exactly true' : 'Input is exactly false';
+ case 'number':
+ if (input === 0) {
+ return 'Input is zero';
+ } else if (input > 0) {
+ return 'Input is a positive number';
+ } else {
+ return 'Input is a negative number';
+ }
+ case 'string':
+ if (input === 'hello') {
+ return `Input is the string '${input}'`;
+ } else {
+ return 'Input is another string';
+ }
+ default:
+ return 'Unknown input';
+ }
+ };
-console.log(analyzeInput(true)); // => "Input is exactly true"
-console.log(analyzeInput(false)); // => "Input is exactly false"
-console.log(analyzeInput(0)); // => "Input is zero"
-console.log(analyzeInput(42)); // => "Input is a positive number"
-console.log(analyzeInput(-7)); // => "Input is a negative number"
-console.log(analyzeInput('hello')); // => "Input is the string 'hello'"
-console.log(analyzeInput('world')); // => "Input is another string"
-console.log(analyzeInput('')); // => "Input is another string"
-console.log(analyzeInput(undefined)); // => "Unknown input"
-console.log(analyzeInput(null)); // => "Unknown input"
+ console.log(typeof undefined, typeof null);
-// Übung 14: Equality Narrowing in einer Funktion implementieren
-// Vervollständige die Funktion analyzeInput so, dass sie zurückgegeben wird:
+ console.log(analyzeInput(true)); // => "Input is exactly true"
+ console.log(analyzeInput(false)); // => "Input is exactly false"
+ console.log(analyzeInput(0)); // => "Input is zero"
+ console.log(analyzeInput(42)); // => "Input is a positive number"
+ console.log(analyzeInput(-7)); // => "Input is a negative number"
+ console.log(analyzeInput('hello')); // => "Input is the string 'hello'"
+ console.log(analyzeInput('world')); // => "Input is another string"
+ console.log(analyzeInput('')); // => "Input is another string"
+ console.log(analyzeInput(undefined)); // => "Unknown input"
+ console.log(analyzeInput(null)); // => "Unknown input"
-// "Input is exactly true" wenn input === true.
+ // Übung 14: Equality Narrowing in einer Funktion implementieren
+ // Vervollständige die Funktion analyzeInput so, dass sie zurückgegeben wird:
-// "Input is exactly false" wenn input === false.
+ // [x] "Input is exactly true" wenn input === true.
+ // [x] "Input is exactly false" wenn input === false.
+ // [x] "Input is zero" wenn input === 0.
+ // [x] "Input is a positive number" wenn input eine Zahl größer als null ist.
+ // [x] "Input is a negative number" wenn input eine Zahl kleiner als null ist.
+ // [x] "Input is the string 'hello'" wenn input === "hello".
+ // [x] "Input is another string" wenn input irgendein anderer String ist.
+ // [x] "Unknown input" andernfalls.
-// "Input is zero" wenn input === 0.
-
-// "Input is a positive number" wenn input eine Zahl größer als null ist.
-
-// "Input is a negative number" wenn input eine Zahl kleiner als null ist.
-
-// "Input is the string 'hello'" wenn input === "hello".
-
-// "Input is another string" wenn input irgendein anderer String ist.
-
-// "Unknown input" andernfalls.
-
-// Verwende Equality- und Vergleichsoperatoren, um den Typ und den Wert der Eingabe einzugrenzen.
+ // Verwende Equality- und Vergleichsoperatoren, um den Typ und den Wert der Eingabe einzugrenzen.
+}
diff --git a/04_typescript/uebungen/15_narrowing-in-operator/src/main.ts b/04_typescript/uebungen/15_narrowing-in-operator/src/main.ts
index 9bdb347..ceed89d 100644
--- a/04_typescript/uebungen/15_narrowing-in-operator/src/main.ts
+++ b/04_typescript/uebungen/15_narrowing-in-operator/src/main.ts
@@ -1,14 +1,26 @@
-type Guitar = { strum: () => void };
-type Piano = { pressKeys: () => void };
+{
+ type Guitar = { strum: () => void };
+ type Piano = { pressKeys: () => void };
-const play = (instrument: Guitar | Piano) => {
- // Your code here
-};
+ const play = (instrument: Guitar | Piano) => {
+ if ('strum' in instrument) {
+ instrument.strum();
+ } else {
+ instrument.pressKeys();
+ }
+ };
-// Create guitar instance
+ // Create guitar instance
+ const guitar: Guitar = {
+ strum: () => console.log('Strumming the guitar!'),
+ };
-// Create piano instance
+ // Create piano instance
+ const piano: Piano = {
+ pressKeys: () => console.log('Pressing piano keys!'),
+ };
-// Call functions
-play(guitar); // => "Strumming the guitar!"
-play(piano); // => "Pressing piano keys!"
+ // Call functions
+ play(guitar); // => "Strumming the guitar!"
+ play(piano); // => "Pressing piano keys!"
+}
diff --git a/04_typescript/uebungen/16_narrowing-zuweisung/assets/js/bundle.js b/04_typescript/uebungen/16_narrowing-zuweisung/assets/js/bundle.js
new file mode 100644
index 0000000..0afbb8d
--- /dev/null
+++ b/04_typescript/uebungen/16_narrowing-zuweisung/assets/js/bundle.js
@@ -0,0 +1,31 @@
+(() => {
+ var __getOwnPropNames = Object.getOwnPropertyNames;
+ var __commonJS = (cb, mod) => function __require() {
+ try {
+ return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
+ } catch (e) {
+ throw mod = 0, e;
+ }
+ };
+
+ // src/main.ts
+ var require_main = __commonJS({
+ "src/main.ts"() {
+ var handleValue = (value) => {
+ if (typeof value === "string") {
+ console.log(value.toUpperCase());
+ } else if (typeof value === "number") {
+ console.log(value * 2);
+ }
+ console.log(value ? "It's true!" : "It's false!");
+ };
+ handleValue("hello");
+ handleValue("TypeScript");
+ handleValue(21);
+ handleValue(50);
+ handleValue(false);
+ handleValue(true);
+ }
+ });
+ require_main();
+})();
diff --git a/04_typescript/uebungen/16_narrowing-zuweisung/src/main.ts b/04_typescript/uebungen/16_narrowing-zuweisung/src/main.ts
index 3c73e04..691345a 100644
--- a/04_typescript/uebungen/16_narrowing-zuweisung/src/main.ts
+++ b/04_typescript/uebungen/16_narrowing-zuweisung/src/main.ts
@@ -1,11 +1,3 @@
-// Test handleValue with different inputs
-handleValue('hello'); // => "HELLO"
-handleValue('TypeScript'); // => "TYPESCRIPT"
-handleValue(21); // => 42
-handleValue(50); // => 100
-handleValue(false); // => "It's false!"
-handleValue(true); // => "It's true!"
-
// Übung 16: Type Narrowing mit Zuweisungsoperationen
// In dieser Übung arbeitest du mit TypeScripts Features zur Type Narrowing durch Zuweisungsoperationen. Du definierst eine Variable mit einem Union Type (string | number | boolean) und demonstrierst, wie TypeScript den Typ dynamisch auf Basis der zugewiesenen Werte einschränkt.
@@ -14,12 +6,27 @@ handleValue(true); // => "It's true!"
// Anweisungen:
-// 1Schreibe eine Funktion handleValue, die einen string | number | boolean Parameter annimmt und je nach Typ des Arguments ein anderes Verhalten protokolliert.
+// 1. Schreibe eine Funktion handleValue, die einen string | number | boolean Parameter annimmt und je nach Typ des Arguments ein anderes Verhalten protokolliert.
-// Wenn es eine string ist, protokolliere die Version in Großbuchstaben.
+const handleValue = (value: string | number | boolean): void => {
+ // Wenn es eine string ist, protokolliere die Version in Großbuchstaben.
+ if (typeof value === 'string') {
+ console.log(value.toUpperCase());
+ // Wenn es sich um eine number handelt, logge ihren Wert multipliziert mit 2.
+ } else if (typeof value === 'number') {
+ console.log(value * 2);
+ // Wenn es eine boolean ist, protokolliere "It's true!" oder "It's false!". Verwende einen ternären Operator.
+ }
-// Wenn es sich um eine number handelt, logge ihren Wert multipliziert mit 2.
-
-// Wenn es eine boolean ist, protokolliere "It's true!" oder "It's false!". Verwende einen ternären Operator.
+ console.log(value ? "It's true!" : "It's false!");
+};
// 2Teste die Funktion mit verschiedenen Eingaben.
+
+// Test handleValue with different inputs
+handleValue('hello'); // => "HELLO"
+handleValue('TypeScript'); // => "TYPESCRIPT"
+handleValue(21); // => 42
+handleValue(50); // => 100
+handleValue(false); // => "It's false!"
+handleValue(true); // => "It's true!"
diff --git a/04_typescript/uebungen/17_narrowing-kontrollfluss/src/main.ts b/04_typescript/uebungen/17_narrowing-kontrollfluss/src/main.ts
index 9daf82d..e173cd4 100644
--- a/04_typescript/uebungen/17_narrowing-kontrollfluss/src/main.ts
+++ b/04_typescript/uebungen/17_narrowing-kontrollfluss/src/main.ts
@@ -1,9 +1,3 @@
-// Test cases
-console.log(handleInput(null)); // => "No value provided"
-console.log(handleInput(true)); // => "True"
-console.log(handleInput('hello')); // => "HELLO"
-console.log(handleInput(5)); // => 25
-
// Übung 17: Kontrollflussanalyse und Type Narrowing
// In dieser Übung erstellst du eine Funktion, die einen Union Type Parameter akzeptiert und demonstriert, wie TypeScript automatisch eine Type Narrowing basierend auf dem Kontrollfluss durchführt.
@@ -13,15 +7,25 @@ console.log(handleInput(5)); // => 25
// Anweisungen:
// 1 Erstelle eine Funktion handleInput, die einen Parameter vom Typ string | number | boolean | null akzeptiert.
-
// 2 Verwende innerhalb der Funktion die Blöcke if, else if und else, um verschiedene Typen zu behandeln:
-// Wenn die input null ist, gibst du "No value provided" zurück.
-
-// Wenn die input eine boolean ist, wird "True" oder "False" zurückgegeben.
-
-// Wenn input eine string ist, wird die Großbuchstabenversion der Zeichenkette zurückgegeben.
-
-// Wenn input eine number ist, wird das Quadrat der Zahl zurückgegeben.
+const handleInput = (value: string | number | boolean | null): string | number => {
+ if (typeof value === 'number') {
+ return value * value;
+ // Wenn die input eine boolean ist, wird "True" oder "False" zurückgegeben.
+ } else if (typeof value === 'boolean') {
+ return value ? 'True' : 'False';
+ // Wenn input eine string ist, wird die Großbuchstabenversion der Zeichenkette zurückgegeben.
+ } else if (typeof value === 'string') {
+ return value.toUpperCase();
+ // Wenn input eine number ist, wird das Quadrat der Zahl zurückgegeben.
+ }
+ // Wenn die input null ist, gibst du "No value provided" zurück.
+ return 'No value provided';
+};
// 3 Teste die Funktion mit verschiedenen Eingaben, um zu überprüfen, ob TypeScript die Typen korrekt eingrenzt.
+console.log(handleInput(null)); // => "No value provided"
+console.log(handleInput(true)); // => "True"
+console.log(handleInput('hello')); // => "HELLO"
+console.log(handleInput(5)); // => 25
diff --git a/04_typescript/uebungen/18_type-predicates/src/main.ts b/04_typescript/uebungen/18_type-predicates/src/main.ts
index 2c090f3..896b4b5 100644
--- a/04_typescript/uebungen/18_type-predicates/src/main.ts
+++ b/04_typescript/uebungen/18_type-predicates/src/main.ts
@@ -1,11 +1,3 @@
-// Test the filtered array
-const cars = vehicles.filter(isCar);
-cars.forEach((car) => car.drive()); // => "Car driving"
-
-// Test handleVehicle with both Car and Truck
-handleVehicle({ drive: () => console.log('Car driving') }); // => "Car driving"
-handleVehicle({ loadCargo: () => console.log('Truck loading cargo') }); // => "Truck loading cargo"
-
// Übung 18: Type Predicates implementieren
// In dieser Aufgabe definierst du zwei verschiedene Typen und implementierst eine benutzerdefinierte Predicate Function, um zwischen ihnen zu unterscheiden. Dann benutzt du diese Funktion, um verschiedene Objekte in einem Array zu filtern und zu behandeln.
@@ -14,17 +6,74 @@ handleVehicle({ loadCargo: () => console.log('Truck loading cargo') }); // => "T
// 1 Definiere zwei Typen, Car und Truck, wobei:
// Car hat eine Methode drive().
+type Car = {
+ drive: () => void;
+};
// Truck hat eine Methode loadCargo().
+type Truck = {
+ loadCargo: () => void;
+};
// 2 Erstelle eine Type Predicate Funktion isCar, um zu prüfen, ob ein bestimmtes Fahrzeug ein Car ist und eine Fahrfunktion hat. Hinweis: .drive !== undefined.
+const isCar = (vehicle: Car | Truck): vehicle is Car => {
+ return Object.hasOwn(vehicle, 'drive');
+ return (vehicle as Car).drive !== undefined;
+};
// 3 Implementiere eine Funktion handleVehicle, die einen Parameter vom Typ Car | Truck akzeptiert:
-
-// Wenn das Fahrzeug ein Car ist, rufe drive() an.
-
-// Wenn das Fahrzeug ein Truck ist, rufe loadCargo() an.
+const handleVehicle = (vehicle: Car | Truck) => {
+ // Wenn das Fahrzeug ein Car ist, rufe drive() an.
+ if (isCar(vehicle)) {
+ vehicle.drive();
+ // Wenn das Fahrzeug ein Truck ist, rufe loadCargo() an.
+ } else {
+ vehicle.loadCargo();
+ }
+};
// 4 Erstelle ein Array von Car | Truck Objekten und filtere nur die Autos mit dem isCar Predicate heraus.
+const vehicles: (Car | Truck)[] = [
+ {
+ drive: () => {
+ console.log('Car driving');
+ },
+ },
+ {
+ loadCargo: () => {
+ console.log('Truck loading cargo!');
+ },
+ },
+ {
+ drive: () => {
+ console.log('Car driving');
+ },
+ },
+ {
+ drive: () => {
+ console.log('Car driving');
+ },
+ },
+ {
+ drive: () => {
+ console.log('Car driving');
+ },
+ },
+];
// 5 Teste deine Funktionen mit verschiedenen Eingaben.
+
+// Test the filtered array
+// const cars = vehicles.filter(isCar);
+const cars = vehicles.filter((vehicle) => {
+ return isCar(vehicle);
+});
+cars.forEach((car) => {
+ car.drive();
+}); // => "Car driving"
+
+console.log('Filter End');
+
+// Test handleVehicle with both Car and Truck
+handleVehicle({ drive: () => console.log('Car driving') }); // => "Car driving"
+handleVehicle({ loadCargo: () => console.log('Truck loading cargo') }); // => "Truck loading cargo"
diff --git a/04_typescript/uebungen/19_fn-typausdruecke/src/main.ts b/04_typescript/uebungen/19_fn-typausdruecke/src/main.ts
index 1f02bac..1446a1f 100644
--- a/04_typescript/uebungen/19_fn-typausdruecke/src/main.ts
+++ b/04_typescript/uebungen/19_fn-typausdruecke/src/main.ts
@@ -1,17 +1,29 @@
-// Test cases
-console.log(calculate(add, 10, 5)); // => 15
-console.log(calculate(multiply, 10, 5)); // => 50
+{
+ // Übung 19: Arbeiten mit Function Type Expressions
-// Übung 19: Arbeiten mit Function Type Expressions
+ // In dieser Aufgabe schreibst du eine Funktion, die andere Funktionen als Parameter akzeptiert und Logik basierend auf diesen Function Type Expressions implementiert.
-// In dieser Aufgabe schreibst du eine Funktion, die andere Funktionen als Parameter akzeptiert und Logik basierend auf diesen Function Type Expressions implementiert.
+ // Anweisungen:
-// Anweisungen:
+ // 1 Definiere einen Type Alias MathOperation für eine Funktion, die zwei numbers als Parameter nimmt und einen number zurückgibt.
+ type MathOperation = (x: number, y: number) => number;
-// 1 Definiere einen Type Alias MathOperation für eine Funktion, die zwei numbers als Parameter nimmt und einen number zurückgibt.
+ // 2 Implementiere eine Funktion calculate, die eine Funktion vom Typ MathOperation und zwei numbers annimmt und die Funktion auf die Zahlen anwendet.
+ const calculate = (func: MathOperation, a: number, b: number): number => {
+ return func(a, b);
+ };
-// 2 Implementiere eine Funktion calculate, die eine Funktion vom Typ MathOperation und zwei numbers annimmt und die Funktion auf die Zahlen anwendet.
+ // 3 Erstelle zwei neue Funktionen, add und multiply, die der Signatur MathOperation entsprechen.
+ const add: MathOperation = (a, b) => {
+ return a + b;
+ };
-// 3 Erstelle zwei neue Funktionen, add und multiply, die der Signatur MathOperation entsprechen.
+ const multiply: MathOperation = (a: number, b: number): number => {
+ return a * b;
+ };
-// 4 Teste alle Funktionen, indem du geeignete Argumente übergibst und die Ergebnisse protokollierst.
+ // 4 Teste alle Funktionen, indem du geeignete Argumente übergibst und die Ergebnisse protokollierst.
+ // Test cases
+ console.log(calculate(add, 10, 5)); // => 15
+ console.log(calculate(multiply, 10, 5)); // => 50
+}
diff --git a/04_typescript/uebungen/20_fn-call-signatures/index.html b/04_typescript/uebungen/20_fn-call-signatures/index.html
new file mode 100644
index 0000000..a515ef4
--- /dev/null
+++ b/04_typescript/uebungen/20_fn-call-signatures/index.html
@@ -0,0 +1,62 @@
+
+
+
+ In dieser Übung erstellst und verwendest du ein paar einfache
+ Funktionen, die sich an bestimmte Call Signatures für die Arbeit mit
+ Zahlen halten.
+
+
+
Anweisungen:
+
+
+ Definiere eine Funktion vom Typ
+ NumberOperation, die ein einzelnes
+ number annimmt und ein
+ number zurückgibt.
+
+
+ Implementiere zwei Funktionen,
+ double und halve, die der Call Signature
+ NumberOperation folgen:
+
+
+
+ double: Multipliziert die eingegebene Zahl mit 2.
+
+
halve: Teilt die eingegebene Zahl durch 2.
+
+
+
+ Definiere einen Objekttyp
+ DescribableNumberOperation mit einer
+ description-Property vom Typ string und einer Cal
+ Signature, die NumberOperation entspricht.
+
+
+ Implementiere eine Funktion
+ describeAndApply, die ein
+ DescribableNumberOperation
+ Objekt annimmt, dessen description protokolliert und
+ die Operation auf eine bestimmte Zahl anwendet.
+
+
Teste alle Funktionen mit ein paar Zahlen.
+
+
+
+
+
+
diff --git a/04_typescript/uebungen/20_fn-call-signatures/package.json b/04_typescript/uebungen/20_fn-call-signatures/package.json
new file mode 100644
index 0000000..61f867a
--- /dev/null
+++ b/04_typescript/uebungen/20_fn-call-signatures/package.json
@@ -0,0 +1,13 @@
+{
+ "name": "20_fn-call-signatures",
+ "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": "commonjs"
+}
diff --git a/04_typescript/uebungen/20_fn-call-signatures/src/main.ts b/04_typescript/uebungen/20_fn-call-signatures/src/main.ts
new file mode 100644
index 0000000..618142b
--- /dev/null
+++ b/04_typescript/uebungen/20_fn-call-signatures/src/main.ts
@@ -0,0 +1,38 @@
+// Step 1: Define the NumberOperation call signature
+
+// Step 2: Implement double and halve functions
+
+// Step 3: Define the DescribableNumberOperation type
+
+// Step 4: Implement describeAndApply function
+
+// Test all functions
+const describableDouble: DescribableNumberOperation = Object.assign(double, {
+ description: 'This operation doubles the number.',
+});
+
+const describableHalve: DescribableNumberOperation = Object.assign(halve, {
+ description: 'This operation halves the number.',
+});
+
+console.log(describeAndApply(describableDouble, 10)); // => 20
+console.log(describeAndApply(describableHalve, 10)); // => 5
+
+// Übung 20: Call Signatures für Zahlenoperationen
+
+// In dieser Übung erstellst und verwendest du ein paar einfache Funktionen, die sich an bestimmte Call Signatures für die Arbeit mit Zahlen halten.
+
+// Anweisungen:
+
+// 1 Definiere eine Funktion vom Typ NumberOperation, die ein einzelnes number annimmt und ein number zurückgibt.
+
+// 2 Implementiere zwei Funktionen, double und halve, die der Call Signature NumberOperation folgen:
+
+// double: Multipliziert die eingegebene Zahl mit 2.
+// halve: Teilt die eingegebene Zahl durch 2.
+
+// 3 Definiere einen Objekttyp DescribableNumberOperation mit einer description-Property vom Typ string und einer Cal Signature, die NumberOperation entspricht.
+
+// 4 Implementiere eine Funktion describeAndApply, die ein DescribableNumberOperation Objekt annimmt, dessen description protokolliert und die Operation auf eine bestimmte Zahl anwendet.
+
+// 5 Teste alle Funktionen mit ein paar Zahlen.
diff --git a/04_typescript/uebungen/21_fn-identity/index.html b/04_typescript/uebungen/21_fn-identity/index.html
new file mode 100644
index 0000000..3720296
--- /dev/null
+++ b/04_typescript/uebungen/21_fn-identity/index.html
@@ -0,0 +1,53 @@
+
+
+
+
+
+ Übung 21: Eine allgemeine Identitätsfunktion erstellen
+
+
+
+
+
+
+
+
Übung 21: Eine allgemeine Identitätsfunktion erstellen
+
+ In dieser Übung erstellst du eine einfache generische Funktion
+ namens identity, die den ihr übergebenen Wert
+ zurückgibt. So lernst du, wie generische Funktionen mit
+ verschiedenen Typen arbeiten können, ohne die Typsicherheit zu
+ verlieren.
+
+
+
Anweisungen:
+
+
+ Implementiere eine generische identity Funktion, die
+ einen Parameter vom Typ T annimmt und denselben Wert
+ zurückgibt.
+
+
+ Rufe identity mit einer number auf und
+ speichere das Ergebnis.
+
+
+ Rufe identity mit einer string auf und
+ speichere das Ergebnis.
+
+
+ Rufe identity mit einem Array von Objekten auf und
+ speichere das Ergebnis.
+
+
+ Stelle sicher, dass TypeScript die Rückgabetypen ohne explicit
+ Type Annotations korrekt herleitet.
+
+
+
+
+
+
+
diff --git a/04_typescript/uebungen/21_fn-identity/package.json b/04_typescript/uebungen/21_fn-identity/package.json
new file mode 100644
index 0000000..8427e8d
--- /dev/null
+++ b/04_typescript/uebungen/21_fn-identity/package.json
@@ -0,0 +1,13 @@
+{
+ "name": "21_fn-identity",
+ "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": "commonjs"
+}
diff --git a/04_typescript/uebungen/21_fn-identity/src/main.ts b/04_typescript/uebungen/21_fn-identity/src/main.ts
new file mode 100644
index 0000000..121ac97
--- /dev/null
+++ b/04_typescript/uebungen/21_fn-identity/src/main.ts
@@ -0,0 +1,15 @@
+// Übung 21: Eine allgemeine Identitätsfunktion erstellen
+
+// In dieser Übung erstellst du eine einfache generische Funktion namens identity, die den ihr übergebenen Wert zurückgibt. So lernst du, wie generische Funktionen mit verschiedenen Typen arbeiten können, ohne die Typsicherheit zu verlieren.
+
+// Anweisungen:
+
+// 1 Implementiere eine generische identity Funktion, die einen Parameter vom Typ T annimmt und denselben Wert zurückgibt.
+
+// 2 Rufe identity mit einer number auf und speichere das Ergebnis.
+
+// 3 Rufe identity mit einer string auf und speichere das Ergebnis.
+
+// 4 Rufe identity mit einem Array von Objekten auf und speichere das Ergebnis.
+
+// 5 Stelle sicher, dass TypeScript die Rückgabetypen ohne explicit Type Annotations korrekt herleitet.
diff --git a/04_typescript/uebungen/22_fn-optional-props/index.html b/04_typescript/uebungen/22_fn-optional-props/index.html
new file mode 100644
index 0000000..603c443
--- /dev/null
+++ b/04_typescript/uebungen/22_fn-optional-props/index.html
@@ -0,0 +1,49 @@
+
+
+
+
+
+ Übung 22: Optionale Parameter implementieren
+
+
+
+
+
+
+
+
Übung 22: Optionale Parameter implementieren
+
+ Erstelle die Funktion createUserProfile, die drei
+ Parameter benötigt: einen obligatorischen username und zwei
+ optionale Parameter, age und email. Die
+ Funktion sollte einen String mit einer Profilzusammenfassung
+ zurückgeben. Wenn keine optionalen Parameter angegeben werden,
+ sollten die Standardwerte verwendet werden, um das Profil zu
+ vervollständigen.
+
+
+
Anweisungen:
+
+
+ Definiere eine Funktion createUserProfile, die
+ akzeptiert:
+
+
username (erforderlich, String)
+
age (optional, Zahl, Standardwert ist 18)
+
+ email (optional, String, Standardwert: "N/A")
+
+
+
+
+ Die Funktion sollte einen String zurückgeben, der das Profil des
+ Nutzers zusammenfasst.
+
+
+
+
+
+
+
diff --git a/04_typescript/uebungen/22_fn-optional-props/package.json b/04_typescript/uebungen/22_fn-optional-props/package.json
new file mode 100644
index 0000000..88e6a06
--- /dev/null
+++ b/04_typescript/uebungen/22_fn-optional-props/package.json
@@ -0,0 +1,13 @@
+{
+ "name": "22_fn-optional-props",
+ "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": "commonjs"
+}
diff --git a/04_typescript/uebungen/22_fn-optional-props/src/main.ts b/04_typescript/uebungen/22_fn-optional-props/src/main.ts
new file mode 100644
index 0000000..0a91631
--- /dev/null
+++ b/04_typescript/uebungen/22_fn-optional-props/src/main.ts
@@ -0,0 +1,19 @@
+createUserProfile('JohnDoe', 25, 'john@example.com');
+// => "User JohnDoe is 25 years old and can be contacted at john@example.com."
+
+createUserProfile('JaneDoe');
+// => "User JaneDoe is 18 years old and can be contacted at N/A."
+
+// Übung 22: Optionale Parameter implementieren
+
+// Erstelle die Funktion createUserProfile, die drei Parameter benötigt: einen obligatorischen username und zwei optionale Parameter, age und email. Die Funktion sollte einen String mit einer Profilzusammenfassung zurückgeben. Wenn keine optionalen Parameter angegeben werden, sollten die Standardwerte verwendet werden, um das Profil zu vervollständigen.
+
+// Anweisungen:
+
+// Definiere eine Funktion createUserProfile, die akzeptiert:
+
+// username (erforderlich, String)
+// age (optional, Zahl, Standardwert ist 18)
+// email (optional, String, Standardwert: "N/A")
+
+// Die Funktion sollte einen String zurückgeben, der das Profil des Nutzers zusammenfasst.
diff --git a/04_typescript/uebungen/23_fn-rest-params-args/index.html b/04_typescript/uebungen/23_fn-rest-params-args/index.html
new file mode 100644
index 0000000..f5de609
--- /dev/null
+++ b/04_typescript/uebungen/23_fn-rest-params-args/index.html
@@ -0,0 +1,58 @@
+
+
+
+
+
+ Übung 23: Restparameter und Restargumente
+
+
+
+
+
+
+
+
Übung 23: Restparameter und Restargumente
+
+ Schreibe zwei Funktionen: eine, die Restparameter verwendet, um eine
+ unterschiedliche Anzahl von Zahlen zu akzeptieren und ihre Summe zu
+ berechnen, und eine andere, die die Spread-Syntax verwendet, um ein
+ Array von Zahlen in einzelne Argumente für eine mathematische
+ Funktion zu verteilen.
+
+
+
Anweisungen:
+
+
+ Definiere eine Funktion sumAll, die einen
+ Restparameter, bestehend aus einer variablen Anzahl von
+ numerischen Argumenten, annimmt und die Summe aller übergebenen
+ Zahlen zurückgibt. Verwende die Methode reduce, um die Summe des
+ Arrays zu berechnen.
+
+
+ Als Nächstes definierst du eine Funktion namens
+ calculateHypotenuse, die zwei Zahlen als Argumente
+ akzeptiert und die Hypotenuse mithilfe der Formel
+ √(a² + b²)
+ berechnet. Du solltest diese Funktion aufrufen, indem du ein Array
+ mit zwei Zahlen mit Hilfe der Spread-Syntax ausbreitest. (Tipp:
+ Verwende Math.sqrt())
+
+
+ Teste schließlich die Funktion sumAll, indem du sie
+ mit mehreren Zahlen aufrufst und das Ergebnis protokollierst.
+ Teste die Funktion calculateHypotenuse, indem du ein
+ Array mit zwei Zahlen erstellst, dieses Array in die Funktion
+ überträgst und das Ergebnis protokollierst. Versuche außerdem,
+ calculateHypotenuse mit einem Array aufzurufen, das
+ nicht genau zwei Zahlen enthält, um das Type-Checking von
+ TypeScript zu beobachten.
+
+
+
+
+
+
+
diff --git a/04_typescript/uebungen/23_fn-rest-params-args/package.json b/04_typescript/uebungen/23_fn-rest-params-args/package.json
new file mode 100644
index 0000000..ad2213f
--- /dev/null
+++ b/04_typescript/uebungen/23_fn-rest-params-args/package.json
@@ -0,0 +1,13 @@
+{
+ "name": "23_fn-rest-params-args",
+ "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": "commonjs"
+}
diff --git a/04_typescript/uebungen/23_fn-rest-params-args/src/main.ts b/04_typescript/uebungen/23_fn-rest-params-args/src/main.ts
new file mode 100644
index 0000000..86f7f17
--- /dev/null
+++ b/04_typescript/uebungen/23_fn-rest-params-args/src/main.ts
@@ -0,0 +1,23 @@
+// Example usage of sumAll
+// Define total
+console.log(total); // => 15
+
+// Example usage of calculateHypotenuse with spread syntax
+// Define hypotenuse
+console.log(hypotenuse); // => 5
+
+// Attempting to call calculateHypotenuse with incorrect number of arguments
+const invalidSides = [3, 4, 5];
+// Define invalidHypotenuse to call calculateHypotenuse with invalidSides => TypeScript Error: Expected 2 arguments, but got 3.
+
+// Übung 23: Restparameter und Restargumente
+
+// Schreibe zwei Funktionen: eine, die Restparameter verwendet, um eine unterschiedliche Anzahl von Zahlen zu akzeptieren und ihre Summe zu berechnen, und eine andere, die die Spread-Syntax verwendet, um ein Array von Zahlen in einzelne Argumente für eine mathematische Funktion zu verteilen.
+
+// Anweisungen:
+
+// 1 Definiere eine Funktion sumAll, die einen Restparameter, bestehend aus einer variablen Anzahl von numerischen Argumenten, annimmt und die Summe aller übergebenen Zahlen zurückgibt. Verwende die Methode reduce, um die Summe des Arrays zu berechnen.
+
+// 2 Als Nächstes definierst du eine Funktion namens calculateHypotenuse, die zwei Zahlen als Argumente akzeptiert und die Hypotenuse mithilfe der Formel √(a² + b²) berechnet. Du solltest diese Funktion aufrufen, indem du ein Array mit zwei Zahlen mit Hilfe der Spread-Syntax ausbreitest. (Tipp: Verwende Math.sqrt())
+
+// 3 Teste schließlich die Funktion sumAll, indem du sie mit mehreren Zahlen aufrufst und das Ergebnis protokollierst. Teste die Funktion calculateHypotenuse, indem du ein Array mit zwei Zahlen erstellst, dieses Array in die Funktion überträgst und das Ergebnis protokollierst. Versuche außerdem, calculateHypotenuse mit einem Array aufzurufen, das nicht genau zwei Zahlen enthält, um das Type-Checking von TypeScript zu beobachten.
diff --git a/04_typescript/uebungen/24_fn-destructuring/index.html b/04_typescript/uebungen/24_fn-destructuring/index.html
new file mode 100644
index 0000000..84a0500
--- /dev/null
+++ b/04_typescript/uebungen/24_fn-destructuring/index.html
@@ -0,0 +1,48 @@
+
+
+
+
+
+ Übung 24: Parameter Destrukturierung
+
+
+
+
+
+
+
+
Übung 24: Parameter Destrukturierung
+
+ In dieser Übung übst du die Anwendung der Parameterdestrukturierung
+ in TypeScript, indem du zwei einfache Funktionen erstellst. Die
+ erste Funktion destrukturiert einen Objektparameter und verwendet
+ einen Standardwert für eine seiner Eigenschaften. Die zweite
+ Funktion destrukturiert einen Array-Parameter. Beide Funktionen
+ enthalten Type Annotations, um sicherzustellen, dass sie die
+ richtige Struktur erhalten.
+
+
+
Anweisungen:
+
+
+ Erstelle eine Funktion displayUserInfo, die die
+ Eigenschaften name und age aus einem
+ Objektparameter destrukturiert und einen Standardwert für
+ age liefert.
+
+
+ Erstelle eine Funktion getFirstTwoElements, die die
+ ersten beiden Elemente aus einem Array-Parameter zerstört.
+
+
+ Teste deine Funktionen, indem du sie mit den richtigen Argumenten
+ aufrufst.
+
+
+
+
+
+
+
diff --git a/04_typescript/uebungen/24_fn-destructuring/package.json b/04_typescript/uebungen/24_fn-destructuring/package.json
new file mode 100644
index 0000000..ee867af
--- /dev/null
+++ b/04_typescript/uebungen/24_fn-destructuring/package.json
@@ -0,0 +1,13 @@
+{
+ "name": "24_fn-destructuring",
+ "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": "commonjs"
+}
diff --git a/04_typescript/uebungen/24_fn-destructuring/src/main.ts b/04_typescript/uebungen/24_fn-destructuring/src/main.ts
new file mode 100644
index 0000000..82a2399
--- /dev/null
+++ b/04_typescript/uebungen/24_fn-destructuring/src/main.ts
@@ -0,0 +1,19 @@
+// Example usage of displayUserInfo
+displayUserInfo({ name: 'John' }); // => Hello, John! You are 25 years old.
+displayUserInfo({ name: 'Alice', age: 30 }); // => Hello, Alice! You are 30 years old.
+
+// Example usage of getFirstTwoElements
+getFirstTwoElements([5, 10]); // => First: 5, Second: 10
+getFirstTwoElements([8]); // => First: 8, Second: undefined
+
+// Übung 24: Parameter Destrukturierung
+
+// In dieser Übung übst du die Anwendung der Parameterdestrukturierung in TypeScript, indem du zwei einfache Funktionen erstellst. Die erste Funktion destrukturiert einen Objektparameter und verwendet einen Standardwert für eine seiner Eigenschaften. Die zweite Funktion destrukturiert einen Array-Parameter. Beide Funktionen enthalten Type Annotations, um sicherzustellen, dass sie die richtige Struktur erhalten.
+
+// Anweisungen:
+
+// 1 Erstelle eine Funktion displayUserInfo, die die Eigenschaften name und age aus einem Objektparameter destrukturiert und einen Standardwert für age liefert.
+
+// 2 Erstelle eine Funktion getFirstTwoElements, die die ersten beiden Elemente aus einem Array-Parameter zerstört.
+
+// 3 Teste deine Funktionen, indem du sie mit den richtigen Argumenten aufrufst.
diff --git a/04_typescript/uebungen/25_obj-read-only/index.html b/04_typescript/uebungen/25_obj-read-only/index.html
new file mode 100644
index 0000000..8b33cab
--- /dev/null
+++ b/04_typescript/uebungen/25_obj-read-only/index.html
@@ -0,0 +1,68 @@
+
+
+
+
+
+ Übung 25: Optionale und readonly Eigenschaften
+
+
+
+
+
+
+
+
Übung 25: Optionale und readonly Eigenschaften
+
+ In dieser Übung erstellst du eine interface für ein
+ »Product«, die erforderliche, optionale und readonly Eigenschaften
+ enthält. Anschließend schreibst du eine Funktion, die Informationen
+ über das Produkt protokolliert und dabei optionale Eigenschaften
+ korrekt behandelt.
+
+
+
Anweisungen:
+
+
+ Definiere ein Product Interface, die Folgendes
+ beinhaltet:
+
+
+ Erforderliche Eigenschaften id (Number) und
+ name (String).
+
+
+ Optionale Eigenschaften price (Number) und
+ description (String).
+
+
+ Eine readonlycategory (String)
+ Eigenschaft.
+
+
+
+
+ Schreibe eine Funktion printProductDetails, die ein
+ Product Objekt annimmt und:
+
+
+ Druckt die name, category und
+ id.
+
+
+ Wenn priceundefined ist, drucke
+ "Price: Not available".
+
+
+ Wenn descriptionundefined ist,
+ drucke "No description availabler".
+
+
+
+
+
+
+
+
+
diff --git a/04_typescript/uebungen/25_obj-read-only/package.json b/04_typescript/uebungen/25_obj-read-only/package.json
new file mode 100644
index 0000000..a5ad3f3
--- /dev/null
+++ b/04_typescript/uebungen/25_obj-read-only/package.json
@@ -0,0 +1,13 @@
+{
+ "name": "25_obj-read-only",
+ "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": "commonjs"
+}
diff --git a/04_typescript/uebungen/25_obj-read-only/src/main.ts b/04_typescript/uebungen/25_obj-read-only/src/main.ts
new file mode 100644
index 0000000..2b0f1e6
--- /dev/null
+++ b/04_typescript/uebungen/25_obj-read-only/src/main.ts
@@ -0,0 +1,17 @@
+// Übung 25: Optionale und readonly Eigenschaften
+
+// In dieser Übung erstellst du eine interface für eine Product, die erforderliche, optionale und readonly Eigenschaften enthält. Anschließend schreibst du eine Funktion, die Informationen über das Produkt protokolliert und dabei optionale Eigenschaften korrekt behandelt.
+
+// Anweisungen:
+
+// 1 Definiere ein Product Interface, die Folgendes beinhaltet:
+
+// Erforderliche Eigenschaften id (Number) und name (String).
+// Optionale Eigenschaften price (Number) und description (String).
+// Eine readonly category (String) Eigenschaft.
+
+// 2 Schreibe eine Funktion printProductDetails, die ein Product Objekt annimmt und:
+
+// Druckt die name, category und id.
+// Wenn price undefined ist, drucke "Price: Not available".
+// Wenn description undefined ist, drucke "No description availabler".
diff --git a/04_typescript/uebungen/26_obj-update/index.html b/04_typescript/uebungen/26_obj-update/index.html
new file mode 100644
index 0000000..b27bf67
--- /dev/null
+++ b/04_typescript/uebungen/26_obj-update/index.html
@@ -0,0 +1,63 @@
+
+
+
+
+
+ Übung 26: Eine verschachtelte Objekteigenschaft aktualisieren
+
+
+
+
+
+
+
+
Übung 26: Eine verschachtelte Objekteigenschaft aktualisieren
+
+ In dieser Übung definierst du ein Interface mit readonly und
+ veränderbaren Eigenschaften und aktualisierst ein verschachteltes
+ Objekt innerhalb des Interfaces. Du übst den Umgang mit
+ verschachtelten Objekten und readonly Eigenschaften.
+
+
+
Anweisungen:
+
+
+ Erstelle ein Employee Interface, die Folgendes
+ enthält:
+
+
+ Eine readonlyemployeeId (Number)
+ Eigenschaft.
+
+
+ Eine veränderbare Detail-Eigenschaft, die ein Objekt ist, das
+ Folgendes enthält: position (String) und
+ salary (Number)
+
+
+
+
+ Schreibe eine Funktion updateEmployeePosition die:
+
+
+ Akzeptiert ein Employee Objekt und einen neuen
+ position String.
+
+
+ Aktualisiert die position des Mitarbeiters,
+ verhindert aber jede Änderung der employeeId.
+
+
+
+
+ Teste die Funktion, indem du ein Employee-Objekt erstellst und die
+ Position aktualisierst.
+
+
+
+
+
+
+
diff --git a/04_typescript/uebungen/26_obj-update/package.json b/04_typescript/uebungen/26_obj-update/package.json
new file mode 100644
index 0000000..9ee6218
--- /dev/null
+++ b/04_typescript/uebungen/26_obj-update/package.json
@@ -0,0 +1,13 @@
+{
+ "name": "26_obj-update",
+ "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": "commonjs"
+}
diff --git a/04_typescript/uebungen/26_obj-update/src/main.ts b/04_typescript/uebungen/26_obj-update/src/main.ts
new file mode 100644
index 0000000..2ca73d2
--- /dev/null
+++ b/04_typescript/uebungen/26_obj-update/src/main.ts
@@ -0,0 +1,19 @@
+// Übung 26: Eine verschachtelte Objekteigenschaft aktualisieren
+
+// In dieser Übung definierst du ein Interface mit readonly und veränderbaren Eigenschaften und aktualisierst ein verschachteltes Objekt innerhalb des Interfaces. Du übst den Umgang mit verschachtelten Objekten und readonly Eigenschaften.
+
+// Anweisungen:
+
+// Erstelle ein Employee Interface, die Folgendes enthält:
+
+// Eine readonly employeeId (Number) Eigenschaft.
+
+// Eine veränderbare Detail-Eigenschaft, die ein Objekt ist, das Folgendes enthält: position (String), salary (Number)
+
+// Schreibe eine Funktion updateEmployeePosition die:
+
+// Akzeptiert ein Employee Objekt und einen neuen position String.
+
+// Aktualisiert die position des Mitarbeiters, verhindert aber jede Änderung der employeeId.
+
+// Teste die Funktion, indem du ein Employee-Objekt erstellst und die Position aktualisierst.
diff --git a/04_typescript/uebungen/27_obj-interface-props/index.html b/04_typescript/uebungen/27_obj-interface-props/index.html
new file mode 100644
index 0000000..9da2cc2
--- /dev/null
+++ b/04_typescript/uebungen/27_obj-interface-props/index.html
@@ -0,0 +1,84 @@
+
+
+
+
+
+
+ Übung 27: Kombiniere Optional, Readonly und Required Properties in einem
+ Interface
+
+
+
+
+
+
+
+
+
+ Übung 27: Kombiniere Optional, Readonly und Required Properties in
+ einem Interface
+
+
+ In dieser Übung erstellst du ein Car Interface mit
+ required, optional und readonly Eigenschaften. Anschließend
+ schreibst du eine Funktion, um ein neues Car Objekt zu
+ erstellen und Änderungen an veränderbaren Eigenschaften zu
+ verarbeiten.
+
+
+
Anweisungen:
+
+
+ Definiere ein Car Interface, die Folgendes
+ beinhaltet:
+
+
+ Erforderliche Eigenschaften make (string) und
+ model (string).
+
+
+ Optionale Eigenschaften year (Number) und
+ color (String).
+
+
+ Eine readonly vin (string) Eigenschaft
+ (Fahrzeugidentifikationsnummer).
+
+
+
+
+ Schreibe eine Funktion createCar die:
+
+
+ Nimmt make, model und
+ vin auf und gibt ein Car Objekt
+ zurück.
+
+
+ Optional können year und color
+ akzeptiert werden.
+
+
+
+
+ Schreibe eine weitere Funktion paintCar die:
+
+
+ Akzeptiert ein Car Objekt und einen neuen
+ color String.
+
+
+ Aktualisiert die color des Fahrzeugs (falls
+ vorhanden), verhindert aber jede Änderung an der
+ vin.
+
+
+
+
+
+
+
+
+
diff --git a/04_typescript/uebungen/27_obj-interface-props/package.json b/04_typescript/uebungen/27_obj-interface-props/package.json
new file mode 100644
index 0000000..b9453a4
--- /dev/null
+++ b/04_typescript/uebungen/27_obj-interface-props/package.json
@@ -0,0 +1,13 @@
+{
+ "name": "27_obj-interface-props",
+ "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": "commonjs"
+}
diff --git a/04_typescript/uebungen/27_obj-interface-props/src/main.ts b/04_typescript/uebungen/27_obj-interface-props/src/main.ts
new file mode 100644
index 0000000..8f3f362
--- /dev/null
+++ b/04_typescript/uebungen/27_obj-interface-props/src/main.ts
@@ -0,0 +1,25 @@
+// Übung 27: Kombiniere Optional, Readonly und Required Properties in einem Interface
+
+// In dieser Übung erstellst du ein Car Interface mit required, optional und readonly Eigenschaften. Anschließend schreibst du eine Funktion, um ein neues Car Objekt zu erstellen und Änderungen an veränderbaren Eigenschaften zu verarbeiten.
+
+// Anweisungen:
+
+// 1 Definiere ein Car Interface, die Folgendes beinhaltet:
+
+// Erforderliche Eigenschaften make (string) und model (string).
+
+// Optionale Eigenschaften year (Number) und color (String).
+
+// Eine readonly vin (string) Eigenschaft (Fahrzeugidentifikationsnummer).
+
+// 2 Schreibe eine Funktion createCar die:
+
+// Nimmt make, model und vin auf und gibt ein Car Objekt zurück.
+
+// Optional können year und color akzeptiert werden.
+
+// 3 Schreibe eine weitere Funktion paintCar die:
+
+// Akzeptiert ein Car Objekt und einen neuen color String.
+
+// Aktualisiert die color des Fahrzeugs (falls vorhanden), verhindert aber jede Änderung an der vin.
diff --git a/04_typescript/uebungen/28_obj-excess-prop-check/index.html b/04_typescript/uebungen/28_obj-excess-prop-check/index.html
new file mode 100644
index 0000000..41e47fa
--- /dev/null
+++ b/04_typescript/uebungen/28_obj-excess-prop-check/index.html
@@ -0,0 +1,53 @@
+
+
+
+
+
+ Übung 28: Excess Property Checks mit Object Literals
+
+
+
+
+
+
+
+
Übung 28: Excess Property Checks mit Object Literals
+
+ In dieser Übung definierst du ein Interface Car und
+ schreibst eine Funktion, die ein Objekt vom Typ
+ Car annimmt. Du wirst untersuchen, wie TypeScript
+ Excess Property Checks erzwingt, indem es versucht, ein Objekt mit
+ zusätzlichen Eigenschaften an die Funktion zu übergeben.
+
+
+
Anweisungen:
+
+
+ Definiere ein Car Interface mit den folgenden
+ Eigenschaften:
+
+
make: String
+
model: String
+
year: Number
+
+
+
+ Schreibe eine Funktion printCarDetails, die ein
+ Objekt vom Typ Car annimmt und die Details des Autos
+ ausgibt (make, model und
+ year).
+
+
+ Versuche, der Funktion ein Objekt zu übergeben, das eine
+ zusätzliche Eigenschaft hat, z. B. color. Beobachte,
+ wie TypeScript mit der überzähligen Eigenschaft umgeht und
+ erkläre, warum der Fehler auftritt.
+
+
+
+
+
+
+
diff --git a/04_typescript/uebungen/28_obj-excess-prop-check/package.json b/04_typescript/uebungen/28_obj-excess-prop-check/package.json
new file mode 100644
index 0000000..0e52588
--- /dev/null
+++ b/04_typescript/uebungen/28_obj-excess-prop-check/package.json
@@ -0,0 +1,13 @@
+{
+ "name": "28_obj-excess-prop-check",
+ "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": "commonjs"
+}
diff --git a/04_typescript/uebungen/28_obj-excess-prop-check/src/main.ts b/04_typescript/uebungen/28_obj-excess-prop-check/src/main.ts
new file mode 100644
index 0000000..b9539bd
--- /dev/null
+++ b/04_typescript/uebungen/28_obj-excess-prop-check/src/main.ts
@@ -0,0 +1,15 @@
+// Übung 28: Excess Property Checks mit Object Literals
+
+// In dieser Übung definierst du ein Interface Car und schreibst eine Funktion, die ein Objekt vom Typ Car annimmt. Du wirst untersuchen, wie TypeScript Excess Property Checks erzwingt, indem es versucht, ein Objekt mit zusätzlichen Eigenschaften an die Funktion zu übergeben.
+
+// Anweisungen:
+
+// 1 Definiere ein Car Interface mit den folgenden Eigenschaften:
+
+// - make: String
+// - model: String
+// - year: Number
+
+// 2 Schreibe eine Funktion printCarDetails, die ein Objekt vom Typ Car annimmt und die Details des Autos ausgibt (make, model und year).
+
+// 3 Versuche, der Funktion ein Objekt zu übergeben, das eine zusätzliche Eigenschaft hat, z. B. color. Beobachte, wie TypeScript mit der überzähligen Eigenschaft umgeht und erkläre, warum der Fehler auftritt.
diff --git a/04_typescript/uebungen/29_obj-extending-interface/index.html b/04_typescript/uebungen/29_obj-extending-interface/index.html
new file mode 100644
index 0000000..23c0bbd
--- /dev/null
+++ b/04_typescript/uebungen/29_obj-extending-interface/index.html
@@ -0,0 +1,43 @@
+
+
+
+
+
+ Übung 29: Extending einer einzelnen Interface
+
+
+
+
+
+
+
+
Übung 29: Extending einer einzelnen Interface
+
+ In dieser Übung wirst du eine bestehende
+ Product Interface erweitern, um einen spezifischeren
+ Typ Electronics zu erstellen. Du wirst zusätzliche
+ Eigenschaften für Elektronikprodukte definieren und ein Objekt des
+ Typs Electronics
+ erstellen.
+
+
+
Anweisungen:
+
+
+ Definiere ein Product Interface mit den Eigenschaften
+ id, name und price.
+
+
+ Erweitere die Product Interface um eine
+ Electronics Interface und füge die Eigenschaften
+ brand und warranty hinzu.
+
+
Erstelle ein Objekt vom Typ Electronics.
+
+
+
+
+
+
diff --git a/04_typescript/uebungen/29_obj-extending-interface/package.json b/04_typescript/uebungen/29_obj-extending-interface/package.json
new file mode 100644
index 0000000..f8c17c8
--- /dev/null
+++ b/04_typescript/uebungen/29_obj-extending-interface/package.json
@@ -0,0 +1,13 @@
+{
+ "name": "29_obj-extending-interface",
+ "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": "commonjs"
+}
diff --git a/04_typescript/uebungen/29_obj-extending-interface/src/main.ts b/04_typescript/uebungen/29_obj-extending-interface/src/main.ts
new file mode 100644
index 0000000..6e135fa
--- /dev/null
+++ b/04_typescript/uebungen/29_obj-extending-interface/src/main.ts
@@ -0,0 +1,11 @@
+// Übung 29: Extending einer einzelnen Interface
+
+// In dieser Übung wirst du eine bestehende Product Interface erweitern, um einen spezifischeren Typ Electronics zu erstellen. Du wirst zusätzliche Eigenschaften für Elektronikprodukte definieren und ein Objekt des Typs Electronics erstellen.
+
+// Anweisungen:
+
+// 1 Definiere ein Product Interface mit den Eigenschaften id, name und price.
+
+// 2 Erweitere die Product Interface um eine Electronics Interface und füge die Eigenschaften brand und warranty hinzu.
+
+// 3 Erstelle ein Objekt vom Typ Electronics.
diff --git a/04_typescript/uebungen/30_obj-subtyp/index.html b/04_typescript/uebungen/30_obj-subtyp/index.html
new file mode 100644
index 0000000..837219e
--- /dev/null
+++ b/04_typescript/uebungen/30_obj-subtyp/index.html
@@ -0,0 +1,47 @@
+
+
+
+
+
+
+ Übung 30: Einzigartige Eigenschaften zu einem Subtyp hinzufügen
+
+
+
+
+
+
+
+
+
+ Übung 30: Einzigartige Eigenschaften zu einem Subtyp hinzufügen
+
+
+ In dieser Übung wirst du die Product Interface
+ erweitern, um einen Typ Furniture zu erstellen, der
+ spezielle Eigenschaften für Möbel hinzufügt, wie
+ material und dimensions.
+
+
+
Anweisungen:
+
+
+ Erweitere die Product Interface, um eine
+ Furniture Interface zu erstellen.
+
+
+ Füge die Eigenschaften material und
+ dimensions zu den Möbeln hinzu.
+
+
+ Erstelle ein Objekt vom Typ Furniture, das ein Möbelstück
+ darstellt.
+
+
+
+
+
+
+
diff --git a/04_typescript/uebungen/30_obj-subtyp/package.json b/04_typescript/uebungen/30_obj-subtyp/package.json
new file mode 100644
index 0000000..9a80620
--- /dev/null
+++ b/04_typescript/uebungen/30_obj-subtyp/package.json
@@ -0,0 +1,13 @@
+{
+ "name": "30_obj-subtyp",
+ "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": "commonjs"
+}
diff --git a/04_typescript/uebungen/30_obj-subtyp/src/main.ts b/04_typescript/uebungen/30_obj-subtyp/src/main.ts
new file mode 100644
index 0000000..b64073b
--- /dev/null
+++ b/04_typescript/uebungen/30_obj-subtyp/src/main.ts
@@ -0,0 +1,11 @@
+// Übung 30: Einzigartige Eigenschaften zu einem Subtyp hinzufügen
+
+// In dieser Übung wirst du die Product Interface erweitern, um einen Typ Furniture zu erstellen, der spezielle Eigenschaften für Möbel hinzufügt, wie material und dimensions.
+
+// Anweisungen:
+
+// 1 Erweitere die Product Interface, um eine Furniture Interface zu erstellen.
+
+// 2 Füge die Eigenschaften material und dimensions zu den Möbeln hinzu.
+
+// 3 Erstelle ein Objekt vom Typ Furniture, das ein Möbelstück darstellt.
diff --git a/04_typescript/uebungen/31_obj-generics-fns/index.html b/04_typescript/uebungen/31_obj-generics-fns/index.html
new file mode 100644
index 0000000..c4ba6f9
--- /dev/null
+++ b/04_typescript/uebungen/31_obj-generics-fns/index.html
@@ -0,0 +1,42 @@
+
+
+
+
+
+ Übung 31: Generic Functions für Arrays
+
+
+
+
+
+
+
+
Übung 31: Generic Functions für Arrays
+
+ In dieser Übung erstellst du eine generische Funktion, die mit
+ Arrays beliebigen Typs funktioniert. Du definierst eine Funktion,
+ die das erste Element des Arrays zurückgibt und es TypeScript
+ ermöglicht, den Elementtyp aus dem übergebenen Array abzuleiten.
+
+
+
Anweisungen:
+
+
+ Definiere eine generische Funktion
+ getFirstElement, die ein Array beliebigen Typs
+ annimmt und das erste Element oder undefined zurückgibt, wenn das
+ Array leer ist.
+
+
+ Rufe die Funktion mit Arrays verschiedener Typen auf
+ (number[], string[], etc.) und
+ protokolliere das Ergebnis.
+
+
+
+
+
+
+
diff --git a/04_typescript/uebungen/31_obj-generics-fns/package.json b/04_typescript/uebungen/31_obj-generics-fns/package.json
new file mode 100644
index 0000000..9af4f66
--- /dev/null
+++ b/04_typescript/uebungen/31_obj-generics-fns/package.json
@@ -0,0 +1,13 @@
+{
+ "name": "31_obj-generics-fns",
+ "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": "commonjs"
+}
diff --git a/04_typescript/uebungen/31_obj-generics-fns/src/main.ts b/04_typescript/uebungen/31_obj-generics-fns/src/main.ts
new file mode 100644
index 0000000..dd947ed
--- /dev/null
+++ b/04_typescript/uebungen/31_obj-generics-fns/src/main.ts
@@ -0,0 +1,9 @@
+// Übung 31: Generic Functions für Arrays
+
+// In dieser Übung erstellst du eine generische Funktion, die mit Arrays beliebigen Typs funktioniert. Du definierst eine Funktion, die das erste Element des Arrays zurückgibt und es TypeScript ermöglicht, den Elementtyp aus dem übergebenen Array abzuleiten.
+
+// Anweisungen:
+
+// 1 Definiere eine generische Funktion getFirstElement, die ein Array beliebigen Typs annimmt und das erste Element oder undefined zurückgibt, wenn das Array leer ist.
+
+// 2 Rufe die Funktion mit Arrays verschiedener Typen auf (number[], string[], etc.) und protokolliere das Ergebnis.
diff --git a/04_typescript/uebungen/uebungen-20-31-ts.zip b/04_typescript/uebungen/uebungen-20-31-ts.zip
new file mode 100644
index 0000000..0485e88
Binary files /dev/null and b/04_typescript/uebungen/uebungen-20-31-ts.zip differ
diff --git a/04_typescript/unterricht/tag32/01_ts-types/src/02_fetch-example.ts b/04_typescript/unterricht/tag32/01_ts-types/src/02_fetch-example.ts
index d73ef9a..5063e95 100644
--- a/04_typescript/unterricht/tag32/01_ts-types/src/02_fetch-example.ts
+++ b/04_typescript/unterricht/tag32/01_ts-types/src/02_fetch-example.ts
@@ -43,6 +43,8 @@
return data;
} catch (err: unknown) {
if (err instanceof Error) {
+ console.log(err.message);
+
console.error(err);
throw err; // paranoid
}
diff --git a/04_typescript/unterricht/tag33/01_ts-types/src/03_type-literale.ts b/04_typescript/unterricht/tag33/01_ts-types/src/03_type-literale.ts
index 6b41187..5a01847 100644
--- a/04_typescript/unterricht/tag33/01_ts-types/src/03_type-literale.ts
+++ b/04_typescript/unterricht/tag33/01_ts-types/src/03_type-literale.ts
@@ -97,5 +97,6 @@
evaluateScore2(Rating.One); // OK
evaluateScore2(Rating.Five); // OK
evaluateScore2(Rating.Four); // OK
+ evaluateScore2(5); // OK
// evaluateScore2(Rating.Six);
}
diff --git a/04_typescript/unterricht/tag33/02_ts-narrowing-guards/src/01_narrowing.ts b/04_typescript/unterricht/tag33/02_ts-narrowing-guards/src/01_narrowing.ts
index d1c0ce3..f756427 100644
--- a/04_typescript/unterricht/tag33/02_ts-narrowing-guards/src/01_narrowing.ts
+++ b/04_typescript/unterricht/tag33/02_ts-narrowing-guards/src/01_narrowing.ts
@@ -2,9 +2,9 @@
{
const displayValue = (value: string | number): void => {
if (typeof value === 'string') {
+ console.log(value.toUpperCase());
// Type Guard: typeof value === "string"
// Narrowing: 'value' is now of type 'string'
- console.log(value.toUpperCase());
} else {
// Narrowing: 'value' is now of type 'number'
console.log(value.toFixed(2));
diff --git a/04_typescript/unterricht/tag33/02_ts-narrowing-guards/src/04_in-operator.ts b/04_typescript/unterricht/tag33/02_ts-narrowing-guards/src/04_in-operator.ts
index c865931..a352f4b 100644
--- a/04_typescript/unterricht/tag33/02_ts-narrowing-guards/src/04_in-operator.ts
+++ b/04_typescript/unterricht/tag33/02_ts-narrowing-guards/src/04_in-operator.ts
@@ -8,6 +8,7 @@ Der In Operator wird verwendet, um zu bestimmen, ob ein Objekt ein bestimmtes Pr
type Car = { drive: () => void };
type Boat = { sail: () => void };
+ // type predicate : vehicle is Car
const isCar = (vehicle: Car | Boat): vehicle is Car => {
return Object.hasOwn(vehicle, 'drive');
};
diff --git a/04_typescript/unterricht/tag33/02_ts-narrowing-guards/src/05_kontrollflussanalyse.ts b/04_typescript/unterricht/tag33/02_ts-narrowing-guards/src/05_kontrollflussanalyse.ts
index 86751d3..6ee624f 100644
--- a/04_typescript/unterricht/tag33/02_ts-narrowing-guards/src/05_kontrollflussanalyse.ts
+++ b/04_typescript/unterricht/tag33/02_ts-narrowing-guards/src/05_kontrollflussanalyse.ts
@@ -25,6 +25,7 @@ Type Narrowing wird verwendet, um den Typ einer Variablen zu beschränken, wenn
if (typeof value === 'string') {
return `String: ${value}`; // early return bei Narrowing
}
+
return `Number: ${value.toFixed(2)}`;
};
@@ -34,13 +35,12 @@ Type Narrowing wird verwendet, um den Typ einer Variablen zu beschränken, wenn
// ---
const describeInput = (input: string | number | null): string => {
if (input === null) {
- return 'No input provided.';
+ return 'No input provided.';
}
if (typeof input === 'string') {
return `String input: ${input.toUpperCase()}`;
}
-
return `Number input: ${input.toFixed(2)}`;
};
diff --git a/04_typescript/unterricht/tag33/02_ts-narrowing-guards/src/06_type-predicate.ts b/04_typescript/unterricht/tag33/02_ts-narrowing-guards/src/06_type-predicate.ts
index c9ab2a8..d3b0a75 100644
--- a/04_typescript/unterricht/tag33/02_ts-narrowing-guards/src/06_type-predicate.ts
+++ b/04_typescript/unterricht/tag33/02_ts-narrowing-guards/src/06_type-predicate.ts
@@ -11,8 +11,9 @@ WICHTIG: "Außerdem grenzt es den Typ der Variablen auf der Grundlage des Ergebn
// "pet is Fish" <- Type predicate
const isFish = (pet: Fish | Bird): pet is Fish => {
- // return 'swim' in pet; // in Operator führt Type- Narrowing durch.
+ //return 'swim' in pet; // in Operator führt Type- Narrowing durch.
return Object.hasOwn(pet, 'swim');
+ // return pet.hasOwnProperty('swim');
// return (pet as Fish).swim !== undefined;
};
diff --git a/04_typescript/unterricht/tag34/01_ts-functions/assets/img/Understand-Typescript.jpg b/04_typescript/unterricht/tag34/01_ts-functions/assets/img/Understand-Typescript.jpg
new file mode 100644
index 0000000..c3a5d16
Binary files /dev/null and b/04_typescript/unterricht/tag34/01_ts-functions/assets/img/Understand-Typescript.jpg differ
diff --git a/04_typescript/unterricht/tag34/01_ts-functions/assets/js/01_fn-type-expression.js b/04_typescript/unterricht/tag34/01_ts-functions/assets/js/01_fn-type-expression.js
new file mode 100644
index 0000000..9fead3d
--- /dev/null
+++ b/04_typescript/unterricht/tag34/01_ts-functions/assets/js/01_fn-type-expression.js
@@ -0,0 +1,45 @@
+(() => {
+ // src/01_fn-type-expression.ts
+ {
+ let printToConsole = function(s) {
+ console.log(s);
+ }, mathOperation = function(fn) {
+ return fn(10, 20);
+ };
+ const mathOperationFn = (fn) => {
+ return fn(4, 5);
+ };
+ const multiply = (a, b) => {
+ return a * b;
+ };
+ const multiply2 = (a, b) => {
+ return a * b;
+ };
+ console.log(multiply2(2, 4));
+ mathOperationFn(multiply);
+ const greeter = (fn) => {
+ fn("Hello, World");
+ };
+ const greeter2 = (fn) => {
+ fn("Hello, World");
+ };
+ greeter(printToConsole);
+ greeter2(printToConsole);
+ const logMessage = (message) => {
+ console.log(message);
+ };
+ const logMessage2 = (message) => {
+ console.log(message);
+ };
+ const logMessage3 = (message) => {
+ console.log(message);
+ };
+ logMessage("Hello");
+ logMessage2("Hola");
+ logMessage3("Hallo");
+ const subtract = (x, y) => {
+ return x - y;
+ };
+ console.log(mathOperation(subtract));
+ }
+})();
diff --git a/04_typescript/unterricht/tag34/01_ts-functions/assets/js/02_fn-call-signature.js b/04_typescript/unterricht/tag34/01_ts-functions/assets/js/02_fn-call-signature.js
new file mode 100644
index 0000000..1c548bc
--- /dev/null
+++ b/04_typescript/unterricht/tag34/01_ts-functions/assets/js/02_fn-call-signature.js
@@ -0,0 +1,29 @@
+(() => {
+ // src/02_fn-call-signature.ts
+ {
+ let doSomething = function(fn) {
+ console.log(fn.description + " returned " + fn(6));
+ };
+ const sum = (a, b) => {
+ return `The sum is ${a + b}`;
+ };
+ const sum2 = (a, b) => {
+ return `The sum is ${a + b}`;
+ };
+ console.log(sum(40, 2));
+ console.log(sum2(60, 7));
+ const add = (x, y) => {
+ return x + y;
+ };
+ const multiply = (x, y) => {
+ return x * y;
+ };
+ console.log(add(123, 321));
+ console.log(multiply(25, 25));
+ const myFunc = (someArg) => {
+ return someArg > 3;
+ };
+ myFunc.description = "Default description";
+ doSomething(myFunc);
+ }
+})();
diff --git a/04_typescript/unterricht/tag34/01_ts-functions/assets/js/03_fn-generics.js b/04_typescript/unterricht/tag34/01_ts-functions/assets/js/03_fn-generics.js
new file mode 100644
index 0000000..1c87fc0
--- /dev/null
+++ b/04_typescript/unterricht/tag34/01_ts-functions/assets/js/03_fn-generics.js
@@ -0,0 +1,34 @@
+(() => {
+ // src/03_fn-generics.ts
+ {
+ const identityNumber = (arg) => {
+ return arg;
+ };
+ const identityString = (arg) => {
+ return arg;
+ };
+ const identity = (arg) => {
+ return arg;
+ };
+ let resultNumber = identity(42);
+ let resultString = identity("Hello TypeScript");
+ let resultBoolean = identity(true);
+ console.log(resultNumber, resultString, resultBoolean);
+ const firstElement = (arr) => {
+ return arr[0];
+ };
+ console.log(firstElement(["Adel", "Andreas", "Ersin", "Kahleel"]));
+ console.log(firstElement([23, 19, 5, 42, 2, 45]));
+ console.log(
+ firstElement([
+ { firstName: "John", age: 27 },
+ { firstName: "JAne", age: 18 }
+ ])
+ );
+ console.log(firstElement([]));
+ let inferredResult = identity("Hello");
+ let explicitResult = identity(42);
+ console.log(inferredResult);
+ console.log(explicitResult);
+ }
+})();
diff --git a/04_typescript/unterricht/tag34/01_ts-functions/assets/js/04_fn-optional-parameter.js b/04_typescript/unterricht/tag34/01_ts-functions/assets/js/04_fn-optional-parameter.js
new file mode 100644
index 0000000..aa56de4
--- /dev/null
+++ b/04_typescript/unterricht/tag34/01_ts-functions/assets/js/04_fn-optional-parameter.js
@@ -0,0 +1,53 @@
+(() => {
+ // src/04_fn-optional-parameter.ts
+ {
+ const greet = (name) => {
+ if (name) {
+ return `Hello, ${name}!`;
+ } else {
+ return "Hello!";
+ }
+ };
+ console.log(greet());
+ console.log(greet("Alice"));
+ }
+ {
+ const greet = (name = "Guest") => {
+ return `Hello, ${name}!`;
+ };
+ console.log(greet());
+ console.log(greet("Alice"));
+ }
+ {
+ const sendMessage = (message, recipient) => {
+ if (recipient) {
+ return `Message: "${message}" sent to ${recipient}`;
+ } else {
+ return `Message: "${message}" sent to default recipient`;
+ }
+ };
+ console.log(sendMessage("Welcome", "John"));
+ console.log(sendMessage("Welcome"));
+ }
+ {
+ const formatNumber = (num, decimals) => {
+ if (decimals !== void 0) {
+ return num.toFixed(decimals);
+ } else {
+ return num.toString();
+ }
+ };
+ console.log(formatNumber(3.14159, 2));
+ console.log(formatNumber(3.14159));
+ }
+ {
+ const processItems = (items, callback) => {
+ for (let i = 0; i < items.length; i++) {
+ callback(items[i], i);
+ }
+ };
+ processItems(["apple", "banana", "cherry"], (item) => {
+ console.log(item);
+ });
+ }
+})();
diff --git a/04_typescript/unterricht/tag34/01_ts-functions/assets/js/05_fn-rest-parameter.js b/04_typescript/unterricht/tag34/01_ts-functions/assets/js/05_fn-rest-parameter.js
new file mode 100644
index 0000000..ab25184
--- /dev/null
+++ b/04_typescript/unterricht/tag34/01_ts-functions/assets/js/05_fn-rest-parameter.js
@@ -0,0 +1,27 @@
+(() => {
+ // src/05_fn-rest-parameter.ts
+ {
+ const multiply = (n, ...m) => {
+ return m.map((x) => n * x);
+ };
+ const a = multiply(10, 1, 2, 3, 4);
+ console.log(a);
+ console.log(multiply(10));
+ console.log(multiply(2, 2, 3));
+ const greetNames = (greeting, ...names) => {
+ return names.map((name) => {
+ return `${greeting} ${name}`;
+ });
+ };
+ console.log(greetNames("Hello", "John").join("\n"));
+ console.log(greetNames("Hi", "John", "Tick", "Trick", "Track").join("\n"));
+ const concatenate = (...strings) => {
+ return strings.join(" ");
+ };
+ const concatenate2 = (...strings) => {
+ return strings.join(" ");
+ };
+ concatenate("Ich", "bin", "ein", "Text");
+ concatenate2("Ich", "bin", "ein", "Text");
+ }
+})();
diff --git a/04_typescript/unterricht/tag34/01_ts-functions/assets/js/06_fn-destructuring.js b/04_typescript/unterricht/tag34/01_ts-functions/assets/js/06_fn-destructuring.js
new file mode 100644
index 0000000..143b35a
--- /dev/null
+++ b/04_typescript/unterricht/tag34/01_ts-functions/assets/js/06_fn-destructuring.js
@@ -0,0 +1,36 @@
+(() => {
+ // src/06_fn-destructuring.ts
+ {
+ let printCoordinates = function([x, y]) {
+ console.log(`X: ${x}, Y: ${y}`);
+ };
+ const greetUser = (user) => {
+ console.log(`Hello, ${user.name}! You are ${user.age} years old.`);
+ };
+ const greetUser2 = ({ name, age }) => {
+ console.log(`Hello, ${name}! You are ${age} years old.`);
+ };
+ const greetUser3 = ({
+ name,
+ age
+ } = { name: "John", age: 18 }) => {
+ console.log(`Hello, ${name}! You are ${age} years old.`);
+ };
+ greetUser3({ name: "Alice", age: 25 });
+ const greetUser4 = (user) => {
+ const { name, age } = user;
+ console.log(`Hello, ${name}! You are ${age} years old.`);
+ };
+ greetUser4({ name: "Alice", age: 25 });
+ const sum = ({ a, b, c }) => {
+ console.log(a + b + c);
+ };
+ const sum2 = (sumObj) => {
+ const { a, b, c } = sumObj;
+ console.log(a + b + c);
+ };
+ sum({ a: 10, b: 5, c: 15 });
+ sum2({ a: 10, b: 5, c: 15 });
+ printCoordinates([10, 20]);
+ }
+})();
diff --git a/04_typescript/unterricht/tag34/01_ts-functions/assets/js/07_never-void-unknown.js b/04_typescript/unterricht/tag34/01_ts-functions/assets/js/07_never-void-unknown.js
new file mode 100644
index 0000000..f36e7ea
--- /dev/null
+++ b/04_typescript/unterricht/tag34/01_ts-functions/assets/js/07_never-void-unknown.js
@@ -0,0 +1,76 @@
+(() => {
+ // src/07_never-void-unknown.ts
+ {
+ let infiniteLoop = function() {
+ while (true) {
+ console.log("This loop will never end");
+ }
+ };
+ const logMessage = (message) => {
+ console.log(message);
+ };
+ const logMessage2 = (message) => {
+ console.log(message);
+ return "message";
+ };
+ logMessage("Hello, TypeScript!");
+ console.log(logMessage2("Hello, TypeScript!"));
+ const clearScreen = () => {
+ };
+ clearScreen();
+ const processInput = (input) => {
+ if (typeof input === "string") {
+ console.log(`The input is a string: ${input.toUpperCase()}`);
+ } else if (typeof input === "number") {
+ console.log(`The input is a number: ${input + 10}`);
+ } else {
+ console.log("Unknown type of input");
+ }
+ };
+ processInput("Hello");
+ processInput(42);
+ processInput(true);
+ const getPersonAsync = async () => {
+ try {
+ const res = await fetch("https://dummyjson.com/users/1?select=firstName,lastName,age");
+ if (!res.ok) {
+ throw Error(`HTTP-Request went wrong: ${res.status}`);
+ }
+ const data = await res.json();
+ return data;
+ } catch (err) {
+ if (err instanceof Error) {
+ console.log(err.message);
+ console.error(err);
+ throw err;
+ }
+ throw new Error("An unknown error occurred.");
+ }
+ };
+ getPersonAsync().then((data) => console.log(data));
+ const safeParse = (s) => {
+ return JSON.parse(s);
+ };
+ const result = safeParse('{"name": "Alice"}');
+ if (typeof result === "object" && result !== null && "name" in result) {
+ console.log(result.name);
+ }
+ const throwError = (message) => {
+ throw new Error(message);
+ };
+ throwError("Something went wrong!");
+ const handleShape = (shape) => {
+ switch (shape) {
+ case "circle":
+ return "Handling a circle";
+ case "square":
+ return "Handling a square";
+ default:
+ const _exhaustiveCheck = shape;
+ return _exhaustiveCheck;
+ }
+ };
+ console.log(handleShape("circle"));
+ console.log(handleShape("square"));
+ }
+})();
diff --git a/04_typescript/unterricht/tag34/01_ts-functions/index.html b/04_typescript/unterricht/tag34/01_ts-functions/index.html
new file mode 100644
index 0000000..bf7a40d
--- /dev/null
+++ b/04_typescript/unterricht/tag34/01_ts-functions/index.html
@@ -0,0 +1,29 @@
+
+
+
+
+
+ TypeScript - Functions
+
+
+
+
+
+
+
+
+
+
+
+
+
TypeScript - Functions
+
+ TypeScript ist eine von Microsoft entwickelte Skriptsprache, die auf den Vorschlägen zum
+ ECMAScript-6-Standardbasiert und statische Typisierung zu JavaScript hinzufügt. Sprachkonstrukte von
+ TypeScript, wie Klassen, Vererbung, Module und anonyme Funktionen, wurden auch in ECMAScript 6 übernommen.
+
+ TypeScript ist eine von Microsoft entwickelte Skriptsprache, die auf den Vorschlägen zum
+ ECMAScript-6-Standardbasiert und statische Typisierung zu JavaScript hinzufügt. Sprachkonstrukte von
+ TypeScript, wie Klassen, Vererbung, Module und anonyme Funktionen, wurden auch in ECMAScript 6 übernommen.
+