This commit is contained in:
Philippe Torrel
2026-07-28 14:03:08 +02:00
parent 0cecd61f11
commit 6bf3c2c7c5
36 changed files with 847 additions and 1 deletions

View File

@@ -0,0 +1,23 @@
<!DOCTYPE html>
<html lang="de">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Übung 4: Vermeiden von any Parametern in Funktionen</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.8/dist/css/bootstrap.min.css" rel="stylesheet" />
<script src="assets/js/bundle.js" defer></script>
</head>
<body>
<main>
<div class="container py-5">
<div class="alert alert-primary">
<h1>Übung 4: Vermeiden von any Parametern in Funktionen</h1>
<p>
Refaktoriere eine Funktion, die den Type any für ihre Parameter verwendet. Ersetze any durch spezifischere
Typen, um die Type-Safety zu verbessern.
</p>
</div>
</div>
</main>
</body>
</html>

View File

@@ -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"
}

View File

@@ -0,0 +1,6 @@
const processData = (input: any): any => {
return input * 2;
};
let result = processData('100');
console.log(result);

View File

@@ -0,0 +1,47 @@
<!DOCTYPE html>
<html lang="de">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Übung 5: Type Annotations in TypeScript-Funktionen</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.8/dist/css/bootstrap.min.css" rel="stylesheet" />
<script src="assets/js/bundle.js" defer></script>
</head>
<body>
<main>
<div class="container py-5">
<div class="alert alert-primary">
<h1>Übung 5: Type Annotations in TypeScript-Funktionen</h1>
<p>
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.
</p>
<p>
Deine Aufgabe ist es, ein einfaches TypeScript-Programm zu erstellen, das die folgenden Schritte ausführt:
</p>
<ol class="list">
<li>
<strong>Deklariere eine Variable</strong>, um den Namen einer Person zu speichern, und gib ihn explizit
als String ein.
</li>
<li>
<strong>Deklariere eine Funktion</strong>, die zwei Parameter, <code>firstName</code> und
<code>lastName</code>, beide vom Typ String, benötigt und einen verketteten vollständigen Namen (ebenfalls
vom Typ String) zurückgibt.
</li>
<li>
<strong>Deklariere eine weitere Funktion</strong>, die die Summe des Zahlenfeldes
<code>[10, 20, 30]</code> berechnet. Diese Funktion sollte das Zahlenfeld als Eingabe haben und die Summe
der Zahlen zurückgeben (der Rückgabetyp sollte Zahl sein).
</li>
<li>
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.
</li>
</ol>
</div>
</div>
</main>
</body>
</html>

View File

@@ -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"
}

View File

@@ -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.

View File

@@ -0,0 +1,58 @@
<!DOCTYPE html>
<html lang="de">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Übung 6: Definieren und Verwenden von Objekttypen mit optionalen Eigenschaften</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.8/dist/css/bootstrap.min.css" rel="stylesheet" />
<script src="assets/js/bundle.js" defer></script>
</head>
<body>
<main>
<div class="container py-5">
<div class="alert alert-primary">
<h2>Übung 6: Definieren und Verwenden von Objekttypen mit optionalen Eigenschaften</h2>
<p>
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.
</p>
<ol class="list">
<li>
Definiere einen Objekttyp Book mit den folgenden Eigenschaften:
<ul>
<li><code>title</code>: Eine Zeichenkette, die den Titel des Buches angibt.</li>
<li><code>author</code>: Eine Zeichenkette, die den Autor des Buches angibt.</li>
<li>
<code>yearPublished</code>: Eine optionale Zahl, die das Jahr angibt, in dem das Buch veröffentlicht
wurde.
</li>
</ul>
</li>
<li>
Implementiere eine Funktion <code>printBookDetails</code>, die einen Parameter vom Typ
<code>Book</code> annimmt und die Details des Buches ausgibt.
<ul>
<li>
Wenn die <code>yearPublished</code> bereitgestellt wird, drucke sie zusammen mit der title und author
aus.
</li>
<li>
Wenn <code>yearPublished</code> nicht angegeben wird, wird eine Meldung gedruckt, die besagt, dass das
Erscheinungsjahr unbekannt ist.
</li>
</ul>
</li>
<li>
Teste die Funktion mit verschiedenen Objekten, die entweder die Eigenschaft
<code>yearPublished</code> enthalten oder nicht.
</li>
</ol>
</div>
</div>
</main>
</body>
</html>

View File

@@ -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"
}

View File

@@ -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 });

View File

@@ -0,0 +1,24 @@
<!DOCTYPE html>
<html lang="de">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Übung 7: Umgang mit Union Types in TypeScript</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.8/dist/css/bootstrap.min.css" rel="stylesheet" />
<script src="assets/js/bundle.js" defer></script>
</head>
<body>
<main>
<div class="container py-5">
<div class="alert alert-primary">
<h2>Übung 7: Umgang mit Union Types in TypeScript</h2>
<p>
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.
</p>
</div>
</div>
</main>
</body>
</html>

View File

@@ -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"
}

View File

@@ -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"
}

View File

@@ -0,0 +1,24 @@
<!DOCTYPE html>
<html lang="de">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Übung 8: Type Aliase in TypeScript verwenden</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.8/dist/css/bootstrap.min.css" rel="stylesheet" />
<script src="assets/js/bundle.js" defer></script>
</head>
<body>
<main>
<div class="container py-5">
<div class="alert alert-primary">
<h2>Übung 8: Type Aliase in TypeScript verwenden</h2>
<p>
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.
</p>
</div>
</div>
</main>
</body>
</html>

View File

@@ -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"
}

View File

@@ -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"

View File

@@ -0,0 +1,25 @@
<!DOCTYPE html>
<html lang="de">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Übung 9: Implementieren und Erweitern von Interfaces in TypeScript</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.8/dist/css/bootstrap.min.css" rel="stylesheet" />
<script src="assets/js/bundle.js" defer></script>
</head>
<body>
<main>
<div class="container py-5">
<div class="alert alert-primary">
<h2>Übung 9: Implementieren und Erweitern von Interfaces in TypeScript</h2>
<p>
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.
</p>
</div>
</div>
</main>
</body>
</html>

View File

@@ -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"
}

View File

@@ -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

View File

@@ -0,0 +1,48 @@
<!DOCTYPE html>
<html lang="de">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Übung 10: Type Assertions in TypeScript anwenden</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.8/dist/css/bootstrap.min.css" rel="stylesheet" />
<script src="assets/js/bundle.js" defer></script>
</head>
<body>
<main>
<div class="container py-5">
<div class="alert alert-primary">
<h2>Übung 10: Type Assertions in TypeScript anwenden</h2>
<p>
In dieser Übung verwendest du Type Assertions, um mit unbekannten Typen zu arbeiten und ein Objekt in einen
benutzerdefinierten Typ zu casten.
</p>
<h4>Anweisungen</h4>
<ul class="list">
<li>Erstelle ein Objekt mysteryObject mit einer Eigenschaft info, die eine Zeichenkette enthält.</li>
<li>Das Objekt sollte vom Typ unknown sein.</li>
<li>Verwende eine Type Assertion, um zu behaupten, dass mysteryObject vom Typ { info: string } ist.</li>
<li>
Greife auf die Info-Eigenschaft von mysteryObject zu und ändere ihren Wert in eine neue Zeichenkette.
</li>
<li>Definiere einen eigenen Typ ComplexObject mit einer Methode compute, die einen String zurückgibt.</li>
<li>
Erstelle ein Objekt basicObject mit einer Methode compute.
<ul>
<li>Die Methode sollte die Zeichenfolge "Basic Computation" zurückgeben.</li>
</ul>
</li>
<li>
Verwende eine zweistufige Type Assertion, um zu behaupten, dass basicObject vom Typ ComplexObject ist.
</li>
<li>Rufe die Berechnungsmethode auf basicObject auf und protokolliere das Ergebnis.</li>
</ul>
</div>
</div>
</main>
</body>
</html>

View File

@@ -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"
}

View File

@@ -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.');
}

View File

@@ -0,0 +1,11 @@
(() => {
// src/main.ts
(() => {
const DOM = {
output: document.querySelector(".output")
};
const init = () => {
};
init();
})();
})();

View File

@@ -0,0 +1,20 @@
<!doctype html>
<html lang="de">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>CreateBtn als Modul</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.8/dist/css/bootstrap.min.css" rel="stylesheet" />
<script src="assets/js/bundle.js" defer></script>
</head>
<body>
<main>
<div class="container py-5">
<h1>CreateBtn als Modul</h1>
<div class="output alert alert-secondary my-3">
Hier sollen 4 verschiedene Buttons erstellt über das <strong>CreateBtn</strong> Modul hinzugefügt werden.
</div>
</div>
</main>
</body>
</html>

View File

@@ -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"
}

View File

@@ -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;

View File

@@ -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();
})();

Binary file not shown.

View File

@@ -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 });
}
})(); })();

View File

@@ -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");
}
})();

View File

@@ -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));
}
})();

View File

@@ -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);
}
})();

View File

@@ -6,7 +6,11 @@
<title>TypeScript - Types</title> <title>TypeScript - Types</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.8/dist/css/bootstrap.min.css" rel="stylesheet" /> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.8/dist/css/bootstrap.min.css" rel="stylesheet" />
<!-- <script src="assets/js/01_grundtypen.js" defer></script> --> <!-- <script src="assets/js/01_grundtypen.js" defer></script> -->
<script src="assets/js/02_fetch-example.js" defer></script> <!-- <script src="assets/js/02_fetch-example.js" defer></script> -->
<!-- <script src="assets/js/03_object-types.js" defer></script> -->
<!-- <script src="assets/js/04_union-types.js" defer></script> -->
<!-- <script src="assets/js/05_type-statement.js" defer></script> -->
<script src="assets/js/06_type-as-statement.js" defer></script>
</head> </head>
<body> <body>
<main> <main>

View File

@@ -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 });
}

View File

@@ -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()
}

View File

@@ -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"
}

View File

@@ -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 = <HTMLParagraphElement>document.querySelector('p');
console.log(pEl?.offsetHeight, paragraphEl.offsetHeight);
}