diff --git a/04_typescript/uebungen/04_without-any/index.html b/04_typescript/uebungen/04_without-any/index.html new file mode 100644 index 0000000..4472844 --- /dev/null +++ b/04_typescript/uebungen/04_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/04_typescript/uebungen/04_without-any/package.json b/04_typescript/uebungen/04_without-any/package.json new file mode 100644 index 0000000..845a96d --- /dev/null +++ b/04_typescript/uebungen/04_without-any/package.json @@ -0,0 +1,13 @@ +{ + "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" +} diff --git a/04_typescript/uebungen/04_without-any/src/main.ts b/04_typescript/uebungen/04_without-any/src/main.ts new file mode 100644 index 0000000..4b8567e --- /dev/null +++ b/04_typescript/uebungen/04_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/04_typescript/uebungen/05_type-annotations/index.html b/04_typescript/uebungen/05_type-annotations/index.html new file mode 100644 index 0000000..b8a134c --- /dev/null +++ b/04_typescript/uebungen/05_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/04_typescript/uebungen/05_type-annotations/package.json b/04_typescript/uebungen/05_type-annotations/package.json new file mode 100644 index 0000000..2907c16 --- /dev/null +++ b/04_typescript/uebungen/05_type-annotations/package.json @@ -0,0 +1,13 @@ +{ + "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" +} diff --git a/04_typescript/uebungen/05_type-annotations/src/main.ts b/04_typescript/uebungen/05_type-annotations/src/main.ts new file mode 100644 index 0000000..b72b5ed --- /dev/null +++ b/04_typescript/uebungen/05_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/04_typescript/uebungen/06_optional-properties/index.html b/04_typescript/uebungen/06_optional-properties/index.html new file mode 100644 index 0000000..1a4f8bd --- /dev/null +++ b/04_typescript/uebungen/06_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/04_typescript/uebungen/06_optional-properties/package.json b/04_typescript/uebungen/06_optional-properties/package.json new file mode 100644 index 0000000..bf98b04 --- /dev/null +++ b/04_typescript/uebungen/06_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/04_typescript/uebungen/06_optional-properties/src/main.ts b/04_typescript/uebungen/06_optional-properties/src/main.ts new file mode 100644 index 0000000..9a8d28a --- /dev/null +++ b/04_typescript/uebungen/06_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/04_typescript/uebungen/07_union-types/index.html b/04_typescript/uebungen/07_union-types/index.html new file mode 100644 index 0000000..6da4066 --- /dev/null +++ b/04_typescript/uebungen/07_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/04_typescript/uebungen/07_union-types/package.json b/04_typescript/uebungen/07_union-types/package.json new file mode 100644 index 0000000..c19d3e0 --- /dev/null +++ b/04_typescript/uebungen/07_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/04_typescript/uebungen/07_union-types/src/main.ts b/04_typescript/uebungen/07_union-types/src/main.ts new file mode 100644 index 0000000..84c25ef --- /dev/null +++ b/04_typescript/uebungen/07_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/04_typescript/uebungen/08_type-aliase/index.html b/04_typescript/uebungen/08_type-aliase/index.html new file mode 100644 index 0000000..d6ffb95 --- /dev/null +++ b/04_typescript/uebungen/08_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/04_typescript/uebungen/08_type-aliase/package.json b/04_typescript/uebungen/08_type-aliase/package.json new file mode 100644 index 0000000..dc6ed54 --- /dev/null +++ b/04_typescript/uebungen/08_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/04_typescript/uebungen/08_type-aliase/src/main.ts b/04_typescript/uebungen/08_type-aliase/src/main.ts new file mode 100644 index 0000000..fd40786 --- /dev/null +++ b/04_typescript/uebungen/08_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/04_typescript/uebungen/09_interfaces/index.html b/04_typescript/uebungen/09_interfaces/index.html new file mode 100644 index 0000000..4b8003b --- /dev/null +++ b/04_typescript/uebungen/09_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/04_typescript/uebungen/09_interfaces/package.json b/04_typescript/uebungen/09_interfaces/package.json new file mode 100644 index 0000000..edefa08 --- /dev/null +++ b/04_typescript/uebungen/09_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/04_typescript/uebungen/09_interfaces/src/main.ts b/04_typescript/uebungen/09_interfaces/src/main.ts new file mode 100644 index 0000000..9bb1fbf --- /dev/null +++ b/04_typescript/uebungen/09_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/04_typescript/uebungen/10_assertions/index.html b/04_typescript/uebungen/10_assertions/index.html new file mode 100644 index 0000000..435e437 --- /dev/null +++ b/04_typescript/uebungen/10_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/04_typescript/uebungen/10_assertions/package.json b/04_typescript/uebungen/10_assertions/package.json new file mode 100644 index 0000000..d294086 --- /dev/null +++ b/04_typescript/uebungen/10_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/04_typescript/uebungen/10_assertions/src/main.ts b/04_typescript/uebungen/10_assertions/src/main.ts new file mode 100644 index 0000000..3a52c34 --- /dev/null +++ b/04_typescript/uebungen/10_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/04_typescript/uebungen/o01_create-btn/assets/js/bundle.js b/04_typescript/uebungen/o01_create-btn/assets/js/bundle.js new file mode 100644 index 0000000..a443d31 --- /dev/null +++ b/04_typescript/uebungen/o01_create-btn/assets/js/bundle.js @@ -0,0 +1,11 @@ +(() => { + // src/main.ts + (() => { + const DOM = { + output: document.querySelector(".output") + }; + const init = () => { + }; + init(); + })(); +})(); diff --git a/04_typescript/uebungen/o01_create-btn/index.html b/04_typescript/uebungen/o01_create-btn/index.html new file mode 100644 index 0000000..3a6bf15 --- /dev/null +++ b/04_typescript/uebungen/o01_create-btn/index.html @@ -0,0 +1,20 @@ + + + + + + CreateBtn als Modul + + + + +
+
+

CreateBtn als Modul

+
+ Hier sollen 4 verschiedene Buttons erstellt über das CreateBtn Modul hinzugefügt werden. +
+
+
+ + diff --git a/04_typescript/uebungen/o01_create-btn/package.json b/04_typescript/uebungen/o01_create-btn/package.json new file mode 100644 index 0000000..f922271 --- /dev/null +++ b/04_typescript/uebungen/o01_create-btn/package.json @@ -0,0 +1,13 @@ +{ + "name": "create-btn", + "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/04_typescript/uebungen/o01_create-btn/src/CreateBtn.ts b/04_typescript/uebungen/o01_create-btn/src/CreateBtn.ts new file mode 100644 index 0000000..6f8b44b --- /dev/null +++ b/04_typescript/uebungen/o01_create-btn/src/CreateBtn.ts @@ -0,0 +1,31 @@ +interface Options {} + +const CreateButton = (options = {}) => { + // Destructuring + const { + classes = [], + iconName = 'circle', + label = 'No Label', + clickHandler = () => { + console.log('no action'); + }, + } = options; + + const btn = document.createElement('button'); + const icon = document.createElement('i'); + const span = document.createElement('span'); + + btn.classList.add('btn', 'btn-sm', ...classes); + icon.classList.add('fas', `fa-${iconName}`); + span.classList.add('visually-hidden'); + span.textContent = label; + + btn.addEventListener('click', clickHandler); + // btn.append(icon,span) + btn.appendChild(icon); + btn.appendChild(span); + + return btn; +}; + +export default CreateButton; diff --git a/04_typescript/uebungen/o01_create-btn/src/main.ts b/04_typescript/uebungen/o01_create-btn/src/main.ts new file mode 100644 index 0000000..88caf2a --- /dev/null +++ b/04_typescript/uebungen/o01_create-btn/src/main.ts @@ -0,0 +1,19 @@ +import CreateBtn from './CreateBtn.ts'; + +(() => { + // === DOM & VARS ======= + const DOM = { + output: document.querySelector('.output') as HTMLDivElement, + }; + + // === INIT ============= + const init = () => {}; + + // === EVENTHANDLER ===== + + // === XHR/FETCH ======== + + // === FUNCTIONS ======== + + init(); +})(); diff --git a/04_typescript/uebungen/uebungen-04-10-o1.zip b/04_typescript/uebungen/uebungen-04-10-o1.zip new file mode 100644 index 0000000..3ed8951 Binary files /dev/null and b/04_typescript/uebungen/uebungen-04-10-o1.zip differ diff --git a/04_typescript/unterricht/tag32/01_ts-types/assets/js/03_object-types.js b/04_typescript/unterricht/tag32/01_ts-types/assets/js/03_object-types.js index 8afef30..95cebd3 100644 --- a/04_typescript/unterricht/tag32/01_ts-types/assets/js/03_object-types.js +++ b/04_typescript/unterricht/tag32/01_ts-types/assets/js/03_object-types.js @@ -1,2 +1,23 @@ (() => { + // src/03_object-types.ts + { + const calculateArea = (rect) => { + console.log("The area of the rectangle is " + rect.width * rect.height); + }; + calculateArea({ width: 5, height: 10 }); + const calculateArea2 = ({ width, height } = { width: 10, height: 10 }) => { + console.log("The area of the rectangle is " + width * height); + }; + calculateArea2({ width: 5, height: 10 }); + const printPersonInfo = (person) => { + console.log("Name: " + person.name); + if (person.age !== void 0) { + console.log("Age: " + person.age.toString()); + } else { + console.log("Age is not provided"); + } + }; + printPersonInfo({ name: "John" }); + printPersonInfo({ name: "Jane", age: 25 }); + } })(); diff --git a/04_typescript/unterricht/tag32/01_ts-types/assets/js/04_union-types.js b/04_typescript/unterricht/tag32/01_ts-types/assets/js/04_union-types.js new file mode 100644 index 0000000..394f6c4 --- /dev/null +++ b/04_typescript/unterricht/tag32/01_ts-types/assets/js/04_union-types.js @@ -0,0 +1,24 @@ +(() => { + // src/04_union-types.ts + { + const printStatus = (status) => { + console.log("Status: ", status); + }; + printStatus(true); + printStatus("loading..."); + const greetPeople = (names) => { + if (Array.isArray(names)) { + console.log("Hello, " + names.join(" and ")); + } else { + console.log("Hello, " + names); + } + }; + greetPeople("John"); + greetPeople(["Ersin", "Kahleel", "Andreas", "Adel"]); + const greetNames = (...names) => { + console.log(`Hello, ${names.join(" and ")}`); + }; + greetNames("John"); + greetNames("Ersin", "Kahleel", "Andreas", "Adel"); + } +})(); diff --git a/04_typescript/unterricht/tag32/01_ts-types/assets/js/05_type-statement.js b/04_typescript/unterricht/tag32/01_ts-types/assets/js/05_type-statement.js new file mode 100644 index 0000000..594d92b --- /dev/null +++ b/04_typescript/unterricht/tag32/01_ts-types/assets/js/05_type-statement.js @@ -0,0 +1,31 @@ +(() => { + // src/05_type-statement.ts + { + 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"); + const capitalize = (input) => { + return input.charAt(0).toUpperCase() + input.slice(1); + }; + const applyTransform = (input, transform) => { + return transform(input); + }; + console.log(applyTransform("hello", capitalize)); + } +})(); diff --git a/04_typescript/unterricht/tag32/01_ts-types/assets/js/06_type-as-statement.js b/04_typescript/unterricht/tag32/01_ts-types/assets/js/06_type-as-statement.js new file mode 100644 index 0000000..5874ace --- /dev/null +++ b/04_typescript/unterricht/tag32/01_ts-types/assets/js/06_type-as-statement.js @@ -0,0 +1,12 @@ +(() => { + // src/06_type-as-statement.ts + { + const h1El = document.querySelector("h1"); + const headlineElement = document.querySelector("h1"); + console.log(h1El); + headlineElement.style.color = "tomato"; + const pEl = document.querySelector("p"); + const paragraphEl = document.querySelector("p"); + console.log(pEl?.offsetHeight, paragraphEl.offsetHeight); + } +})(); diff --git a/04_typescript/unterricht/tag32/01_ts-types/index.html b/04_typescript/unterricht/tag32/01_ts-types/index.html index 3fe3001..2e3ef61 100644 --- a/04_typescript/unterricht/tag32/01_ts-types/index.html +++ b/04_typescript/unterricht/tag32/01_ts-types/index.html @@ -6,7 +6,11 @@ TypeScript - Types - + + + + +
diff --git a/04_typescript/unterricht/tag32/01_ts-types/src/03_object-types.ts b/04_typescript/unterricht/tag32/01_ts-types/src/03_object-types.ts index e69de29..f624cad 100644 --- a/04_typescript/unterricht/tag32/01_ts-types/src/03_object-types.ts +++ b/04_typescript/unterricht/tag32/01_ts-types/src/03_object-types.ts @@ -0,0 +1,59 @@ +// Object Types - bei einem Object Type kann man die Eigenschaften entweder mit einem Komma (,) oder einem Semikolon (;) trennen. Beide sind zulässig +{ + // The parameter's type annotation is an object type + // function calculateArea3(rect: { width: number; height: number }) { + // console.log('The area of the rectangle is ' + rect.width * rect.height); + // } + + // calculateArea3({ width: 5, height: 10 }); + + type RectObj = { width: number; height: number }; + + const calculateArea = (rect: RectObj): void => { + console.log('The area of the rectangle is ' + rect.width * rect.height); + }; + + calculateArea({ width: 5, height: 10 }); + + // ---------------------------- + // Destructuring in der Parameterliste + // const calculateArea2 = (DESTRUCTURING: OBJECT_TYPE = DEFAULT_OBJECT) => {} + const calculateArea2 = ({ width, height }: { width: number; height: number } = { width: 10, height: 10 }): void => { + console.log('The area of the rectangle is ' + width * height); + }; + + calculateArea2({ width: 5, height: 10 }); + + // ---------------------- + + // function printPersonInfo(person: { name: string; age?: number }) { + // console.log('Name: ' + person.name); + // if (person.age !== undefined) { + // console.log('Age: ' + person.age); + // } else { + // console.log('Age is not provided'); + // } + // } + + // interface PersonObj2 { + // name: string; + // age?: number; + // } + type PersonObj = { + name: string; + age?: number; + }; + + const printPersonInfo = (person: PersonObj) => { + console.log('Name: ' + person.name); + if (person.age !== undefined) { + console.log('Age: ' + person.age.toString()); + } else { + console.log('Age is not provided'); + } + }; + + // Both are OK + printPersonInfo({ name: 'John' }); + printPersonInfo({ name: 'Jane', age: 25 }); +} diff --git a/04_typescript/unterricht/tag32/01_ts-types/src/04_union-types.ts b/04_typescript/unterricht/tag32/01_ts-types/src/04_union-types.ts new file mode 100644 index 0000000..7074dd5 --- /dev/null +++ b/04_typescript/unterricht/tag32/01_ts-types/src/04_union-types.ts @@ -0,0 +1,56 @@ +// Union Type - Menge von möglichen Datentyp-Werten erlauben +{ + // function printStatus(status: boolean | string) { + // console.log('Status: ' + status); + // } + + type Status = boolean | string; + + const printStatus = (status: Status): void => { + console.log('Status: ', status); + }; + + // OK + printStatus(true); + + // OK + printStatus('loading...'); + + // Error + // printStatus({ status: 'success' }); + // Argument of type '{ status: string; }' is not assignable to parameter of type 'boolean | string'. + + // ---------------- + + // function greetPeople(names: string | string[]) { + // if (Array.isArray(names)) { + // // TypeScript knows 'names' is a 'string[]' here + // console.log('Hello, ' + names.join(' and ')); + // } else { + // // Here, 'names' is a single 'string' + // console.log('Hello, ' + names); + // } + // } + + const greetPeople = (names: string | string[]): void => { + if (Array.isArray(names)) { + // TypeScript knows 'names' is a 'string[]' here + console.log('Hello, ' + names.join(' and ')); + } else { + // Here, 'names' is a single 'string' + console.log('Hello, ' + names); + } + }; + + greetPeople('John'); + greetPeople(['Ersin', 'Kahleel', 'Andreas', 'Adel']); + + const greetNames = (...names: string[]): void => { + console.log(`Hello, ${names.join(' and ')}`); + }; + + greetNames('John'); + greetNames('Ersin', 'Kahleel', 'Andreas', 'Adel'); + + // example CreateBtn() +} diff --git a/04_typescript/unterricht/tag32/01_ts-types/src/05_type-statement.ts b/04_typescript/unterricht/tag32/01_ts-types/src/05_type-statement.ts new file mode 100644 index 0000000..a7df4f5 --- /dev/null +++ b/04_typescript/unterricht/tag32/01_ts-types/src/05_type-statement.ts @@ -0,0 +1,62 @@ +// 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, feststehende types und unions + + type Car = { + make: string; + model: string; + year: number; + }; + + const printCarDetails = (car: Car): void => { + 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): void => { + 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 Funktionsausdruck + type StringTransform = (input: string) => string; + + const capitalize = (input: string): string => { + return input.charAt(0).toUpperCase() + input.slice(1); + }; + + const applyTransform = (input: string, transform: StringTransform): string => { + return transform(input); + }; + + console.log(applyTransform('hello', capitalize)); // => "Hello" +} diff --git a/04_typescript/unterricht/tag32/01_ts-types/src/06_type-as-statement.ts b/04_typescript/unterricht/tag32/01_ts-types/src/06_type-as-statement.ts new file mode 100644 index 0000000..db3cdda --- /dev/null +++ b/04_typescript/unterricht/tag32/01_ts-types/src/06_type-as-statement.ts @@ -0,0 +1,19 @@ +// Type Assertions verwenden - mit "as" statement festen Datentyp zuweisen +{ + const h1El: HTMLHeadingElement | null = document.querySelector('h1'); + + // selber festgelegt + const headlineElement = document.querySelector('h1') as HTMLHeadingElement; + + console.log(h1El); + + // h1El?.style?.color = 'tomato'; + headlineElement.style.color = 'tomato'; + + const pEl: HTMLParagraphElement | null = document.querySelector('p'); + + // selber festgelegt + const paragraphEl = document.querySelector('p'); + + console.log(pEl?.offsetHeight, paragraphEl.offsetHeight); +}