Work on presentation

This commit is contained in:
Lars Richard committed 2023-06-30 18:54:33 +02:00
1 parent f541a99fca
commit bcb5a1535c
23 files changed
+693 -14

No files matched your search

+143
View File
@@ -107,3 +107,146 @@ const list: List<User> = renderList(users);
const someUser: User = users[0];
[...]
```
# Aufsetzen von Typescript-Projekten
## Installation
```
npm install -g typescript # global
npm install --save-dev typescript # lokal
```
## Neues Projekt
```
tsc --init
```
(Lokal ist der Befehl dann `npx tsc [...]`)
### Konfiguration
tsconfig.json
```json
{
"compilerOptions": {
"target": "es2016",
"module": "commonjs",
"esModuleInterop": true,
"forceConsistentCasingInFileNames": true,
"strict": true
}
}
```
### Kompilieren
```
tsc [<file>]
```
## Integration in Webpack-Applikationen
```
npm install --save-dev typescript ts-loader
```
webpack.config.js
```
module.exports = {
[...]
module: {
rules: [
{
test: /\.tsx?$/,
use: 'ts-loader',
exclude: /node_modules/,
},
],
},
resolve: {
extensions: ['.tsx', '.ts', '.js'],
},
};
```
## Nutzung in Vue3 Applikationen
```
npm install --save-dev typescript
```
tsconfig.json
```json
{
"extends": "@vue/tsconfig/tsconfig.json",
[...]
}
```
```vue
<script lang="ts" setup>
</script>
```
# Migration zu Typescript
Ich habe ein existierendes und großes Javascript Projekt.
Ist der Zug schon abgefahren oder kann ich noch mit Typescript anfangen?
* Javascript darf Typescript importieren, nicht anders herum
* Wenn man doch Javascript importieren muss, gibt es Umwege
## Umwege
Type-Declaration Files
```js
// maximum-number.js
export function maximumNumber(numbers) {
return Math.max(...numbers);
}
```
```ts
// maximum-number.d.ts
export function maximumNumber(numbers: number[]): number;
```
* Keine Implementierung
* Kein Type-Checking der Implementierung
* Schnittstellen werden wenigstens typisiert `¯\_(ツ)_/¯`
* Das geht auch mit JS-Libraries
Unsortiert:
* Types, die man kennen sollte
* Record
* Partial
* Readonly
* union
* intersection
* type vs interface
* typeof
* keyof
* `as` ![img.png](img/trustmebro.png)
* Migration nach Typescript
* Typescript und Vue3
* Wichtige Typescript Konfigurationen
* strict
* noImplicitAny
* strictNullChecks
* strictPropertyInitialization
* useUnknownInCatchVariables
* noUncheckedIndexAccess
* Typescript-ESLint für noch weniger Fehler
* https://typescript-eslint.io/rules/no-floating-promises/
* Type-Narrowing
* Duck-Typing
* Monty python?
* If it quacks like a duck...
* ts-auto-guard
# Reminder: Vortrag in der Entwicklung - Donnerstag (den 06.07.) um 12-13 Uhr mit dem Thema **Typescript**.
> Warum hilft uns Typescript unser Frontend robuster zu gestalten und Fehler vorzubeugen? Wie integriere ich Typescript in bestehende Projekte? Und wie sehen die nützlichsten Features aus?
File renamed without changes.
Binary file not shown.

After

Width:  |  Height:  |  Size: 2.0 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 261 KiB

BIN
View File
Binary file not shown.

After

Width:  |  Height:  |  Size: 941 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 111 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 208 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 76 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 89 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 89 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 87 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 65 KiB

+1
View File
@@ -0,0 +1 @@
export function getFileExtension(path: string): string;
+3
View File
@@ -0,0 +1,3 @@
export function getFileExtension(path) {
return path.split(".").slice(-1);
}
+3
View File
@@ -0,0 +1,3 @@
"use strict";
let variable = 5;
variable = 10;
+3
View File
@@ -0,0 +1,3 @@
let variable: number = 5;
variable = 10;
+28
View File
@@ -0,0 +1,28 @@
{
"name": "live",
"version": "1.0.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "live",
"version": "1.0.0",
"license": "ISC",
"dependencies": {
"typescript": "^5.1.6"
}
},
"node_modules/typescript": {
"version": "5.1.6",
"resolved": "https://registry.npmjs.org/typescript/-/typescript-5.1.6.tgz",
"integrity": "sha512-zaWCozRZ6DLEWAWFrVDz1H6FVXzUSfTy5FUMWsQlU8Ym5JP9eO4xkTIROFCQvhQf61z6O/G6ugw3SgAnvvm+HA==",
"bin": {
"tsc": "bin/tsc",
"tsserver": "bin/tsserver"
},
"engines": {
"node": ">=14.17"
}
}
}
}
+14
View File
@@ -0,0 +1,14 @@
{
"name": "live",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"dependencies": {
"typescript": "^5.1.6"
}
}
+4
View File
@@ -0,0 +1,4 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const extension_js_1 = require("./extension.js");
console.log((0, extension_js_1.getFileExtension)("some/image.png"));
+3
View File
@@ -0,0 +1,3 @@
import {getFileExtension} from './extension.js';
console.log(getFileExtension("some/image.png"));
+109
View File
@@ -0,0 +1,109 @@
{
"compilerOptions": {
/* Visit https://aka.ms/tsconfig to read more about this file */
/* Projects */
// "incremental": true, /* Save .tsbuildinfo files to allow for incremental compilation of projects. */
// "composite": true, /* Enable constraints that allow a TypeScript project to be used with project references. */
// "tsBuildInfoFile": "./.tsbuildinfo", /* Specify the path to .tsbuildinfo incremental compilation file. */
// "disableSourceOfProjectReferenceRedirect": true, /* Disable preferring source files instead of declaration files when referencing composite projects. */
// "disableSolutionSearching": true, /* Opt a project out of multi-project reference checking when editing. */
// "disableReferencedProjectLoad": true, /* Reduce the number of projects loaded automatically by TypeScript. */
/* Language and Environment */
"target": "es2016", /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */
// "lib": [], /* Specify a set of bundled library declaration files that describe the target runtime environment. */
// "jsx": "preserve", /* Specify what JSX code is generated. */
// "experimentalDecorators": true, /* Enable experimental support for legacy experimental decorators. */
// "emitDecoratorMetadata": true, /* Emit design-type metadata for decorated declarations in source files. */
// "jsxFactory": "", /* Specify the JSX factory function used when targeting React JSX emit, e.g. 'React.createElement' or 'h'. */
// "jsxFragmentFactory": "", /* Specify the JSX Fragment reference used for fragments when targeting React JSX emit e.g. 'React.Fragment' or 'Fragment'. */
// "jsxImportSource": "", /* Specify module specifier used to import the JSX factory functions when using 'jsx: react-jsx*'. */
// "reactNamespace": "", /* Specify the object invoked for 'createElement'. This only applies when targeting 'react' JSX emit. */
// "noLib": true, /* Disable including any library files, including the default lib.d.ts. */
// "useDefineForClassFields": true, /* Emit ECMAScript-standard-compliant class fields. */
// "moduleDetection": "auto", /* Control what method is used to detect module-format JS files. */
/* Modules */
"module": "commonjs", /* Specify what module code is generated. */
// "rootDir": "./", /* Specify the root folder within your source files. */
// "moduleResolution": "node10", /* Specify how TypeScript looks up a file from a given module specifier. */
// "baseUrl": "./", /* Specify the base directory to resolve non-relative module names. */
// "paths": {}, /* Specify a set of entries that re-map imports to additional lookup locations. */
// "rootDirs": [], /* Allow multiple folders to be treated as one when resolving modules. */
// "typeRoots": [], /* Specify multiple folders that act like './node_modules/@types'. */
// "types": [], /* Specify type package names to be included without being referenced in a source file. */
// "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */
// "moduleSuffixes": [], /* List of file name suffixes to search when resolving a module. */
// "allowImportingTsExtensions": true, /* Allow imports to include TypeScript file extensions. Requires '--moduleResolution bundler' and either '--noEmit' or '--emitDeclarationOnly' to be set. */
// "resolvePackageJsonExports": true, /* Use the package.json 'exports' field when resolving package imports. */
// "resolvePackageJsonImports": true, /* Use the package.json 'imports' field when resolving imports. */
// "customConditions": [], /* Conditions to set in addition to the resolver-specific defaults when resolving imports. */
// "resolveJsonModule": true, /* Enable importing .json files. */
// "allowArbitraryExtensions": true, /* Enable importing files with any extension, provided a declaration file is present. */
// "noResolve": true, /* Disallow 'import's, 'require's or '<reference>'s from expanding the number of files TypeScript should add to a project. */
/* JavaScript Support */
// "allowJs": true, /* Allow JavaScript files to be a part of your program. Use the 'checkJS' option to get errors from these files. */
// "checkJs": true, /* Enable error reporting in type-checked JavaScript files. */
// "maxNodeModuleJsDepth": 1, /* Specify the maximum folder depth used for checking JavaScript files from 'node_modules'. Only applicable with 'allowJs'. */
/* Emit */
// "declaration": true, /* Generate .d.ts files from TypeScript and JavaScript files in your project. */
// "declarationMap": true, /* Create sourcemaps for d.ts files. */
// "emitDeclarationOnly": true, /* Only output d.ts files and not JavaScript files. */
// "sourceMap": true, /* Create source map files for emitted JavaScript files. */
// "inlineSourceMap": true, /* Include sourcemap files inside the emitted JavaScript. */
// "outFile": "./", /* Specify a file that bundles all outputs into one JavaScript file. If 'declaration' is true, also designates a file that bundles all .d.ts output. */
// "outDir": "./", /* Specify an output folder for all emitted files. */
// "removeComments": true, /* Disable emitting comments. */
// "noEmit": true, /* Disable emitting files from a compilation. */
// "importHelpers": true, /* Allow importing helper functions from tslib once per project, instead of including them per-file. */
// "importsNotUsedAsValues": "remove", /* Specify emit/checking behavior for imports that are only used for types. */
// "downlevelIteration": true, /* Emit more compliant, but verbose and less performant JavaScript for iteration. */
// "sourceRoot": "", /* Specify the root path for debuggers to find the reference source code. */
// "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */
// "inlineSources": true, /* Include source code in the sourcemaps inside the emitted JavaScript. */
// "emitBOM": true, /* Emit a UTF-8 Byte Order Mark (BOM) in the beginning of output files. */
// "newLine": "crlf", /* Set the newline character for emitting files. */
// "stripInternal": true, /* Disable emitting declarations that have '@internal' in their JSDoc comments. */
// "noEmitHelpers": true, /* Disable generating custom helper functions like '__extends' in compiled output. */
// "noEmitOnError": true, /* Disable emitting files if any type checking errors are reported. */
// "preserveConstEnums": true, /* Disable erasing 'const enum' declarations in generated code. */
// "declarationDir": "./", /* Specify the output directory for generated declaration files. */
// "preserveValueImports": true, /* Preserve unused imported values in the JavaScript output that would otherwise be removed. */
/* Interop Constraints */
// "isolatedModules": true, /* Ensure that each file can be safely transpiled without relying on other imports. */
// "verbatimModuleSyntax": true, /* Do not transform or elide any imports or exports not marked as type-only, ensuring they are written in the output file's format based on the 'module' setting. */
// "allowSyntheticDefaultImports": true, /* Allow 'import x from y' when a module doesn't have a default export. */
"esModuleInterop": true, /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables 'allowSyntheticDefaultImports' for type compatibility. */
// "preserveSymlinks": true, /* Disable resolving symlinks to their realpath. This correlates to the same flag in node. */
"forceConsistentCasingInFileNames": true, /* Ensure that casing is correct in imports. */
/* Type Checking */
"strict": true, /* Enable all strict type-checking options. */
// "noImplicitAny": true, /* Enable error reporting for expressions and declarations with an implied 'any' type. */
// "strictNullChecks": true, /* When type checking, take into account 'null' and 'undefined'. */
// "strictFunctionTypes": true, /* When assigning functions, check to ensure parameters and the return values are subtype-compatible. */
// "strictBindCallApply": true, /* Check that the arguments for 'bind', 'call', and 'apply' methods match the original function. */
// "strictPropertyInitialization": true, /* Check for class properties that are declared but not set in the constructor. */
// "noImplicitThis": true, /* Enable error reporting when 'this' is given the type 'any'. */
// "useUnknownInCatchVariables": true, /* Default catch clause variables as 'unknown' instead of 'any'. */
// "alwaysStrict": true, /* Ensure 'use strict' is always emitted. */
// "noUnusedLocals": true, /* Enable error reporting when local variables aren't read. */
// "noUnusedParameters": true, /* Raise an error when a function parameter isn't read. */
// "exactOptionalPropertyTypes": true, /* Interpret optional property types as written, rather than adding 'undefined'. */
// "noImplicitReturns": true, /* Enable error reporting for codepaths that do not explicitly return in a function. */
// "noFallthroughCasesInSwitch": true, /* Enable error reporting for fallthrough cases in switch statements. */
// "noUncheckedIndexedAccess": true, /* Add 'undefined' to a type when accessed using an index. */
// "noImplicitOverride": true, /* Ensure overriding members in derived classes are marked with an override modifier. */
// "noPropertyAccessFromIndexSignature": true, /* Enforces using indexed accessors for keys declared using an indexed type. */
// "allowUnusedLabels": true, /* Disable error reporting for unused labels. */
// "allowUnreachableCode": true, /* Disable error reporting for unreachable code. */
/* Completeness */
// "skipDefaultLibCheck": true, /* Skip type checking .d.ts files that are included with TypeScript. */
"skipLibCheck": true /* Skip type checking all .d.ts files. */
}
}
+21
View File
@@ -1558,6 +1558,20 @@
"node": "*"
}
},
"node_modules/typescript": {
"version": "5.1.6",
"resolved": "https://registry.npmjs.org/typescript/-/typescript-5.1.6.tgz",
"integrity": "sha512-zaWCozRZ6DLEWAWFrVDz1H6FVXzUSfTy5FUMWsQlU8Ym5JP9eO4xkTIROFCQvhQf61z6O/G6ugw3SgAnvvm+HA==",
"optional": true,
"peer": true,
"bin": {
"tsc": "bin/tsc",
"tsserver": "bin/tsserver"
},
"engines": {
"node": ">=14.17"
}
},
"node_modules/uc.micro": {
"version": "1.0.6",
"resolved": "https://registry.npmjs.org/uc.micro/-/uc.micro-1.0.6.tgz",
@@ -2846,6 +2860,13 @@
"resolved": "https://registry.npmjs.org/traverse/-/traverse-0.3.9.tgz",
"integrity": "sha512-iawgk0hLP3SxGKDfnDJf8wTz4p2qImnyihM5Hh/sGvQ3K37dPi/w8sRhdNIxYA1TwFwc5mDhIJq+O0RsvXBKdQ=="
},
"typescript": {
"version": "5.1.6",
"resolved": "https://registry.npmjs.org/typescript/-/typescript-5.1.6.tgz",
"integrity": "sha512-zaWCozRZ6DLEWAWFrVDz1H6FVXzUSfTy5FUMWsQlU8Ym5JP9eO4xkTIROFCQvhQf61z6O/G6ugw3SgAnvvm+HA==",
"optional": true,
"peer": true
},
"uc.micro": {
"version": "1.0.6",
"resolved": "https://registry.npmjs.org/uc.micro/-/uc.micro-1.0.6.tgz",
+361 -14
View File
@@ -6,28 +6,375 @@ backgroundColor: #00437a
color: #fff
---
![bg left:40% 80% drop-shadow:0,0,0,#fff](IServ_Logo_White.png)
# **Typescript**
# **Marp**
![bg left:40% 80% drop-shadow:0,0,0,#fff](img/IServ_Logo_White.png)
Markdown Presentation Ecosystem
https://marp.app/
Endlich ruhig schlafen bei der Frontend-Entwicklung. 😴
---
# How to write slides
# Was ist Typescript?
Split pages by horizontal ruler (`---`). It's very simple! :satisfied:
```markdown
# Slide 1
foobar
Zusatzinformationen über Typen für Javascript.
---
# Slide 2
# Fehlt es Javascript an Types?
foobar
```js
var data; // Was darf hier rein?
```
---
# Fehlt es Javascript an Types?
```js
> var data = "some string";
> console.log(data);
"some string"
> data = 15; // Why not both?
> console.log(data);
15
```
---
# Jetzt mit Types!
---
# Jetzt mit Types!
```ts
var data: string = "some string";
console.log(data);
data = 15; // ❌ Error
console.log(data);
```
---
## Transparenz von Schnittstellen
Was tut diese Library?
```js
// @iserv/graph.js
export function drawGraph(data, options = {}) {
[... Implementierungsdetails]
}
```
---
## Transparenz von Schnittstellen
Was tut diese Library?
```js
// @iserv/graph.js
export function drawGraph(data, options = {}) {
[... Implementierungsdetails]
}
```
Besser: Wie benutze ich diese Library?
---
## Transparenz von Schnittstellen
```js
// @iserv/graph.js
export function drawGraph(data, options = {}) {
[... Implementierungsdetails]
}
// your-module.js
drawGraph([{
x: 2,
y: 5,
}, {
x: 3,
y: 7,
}]);
```
---
## Transparenz von Schnittstellen
```js
// @iserv/graph.js
export function drawGraph(data, options = {}) {
[... Implementierungsdetails]
}
// your-module.js
drawGraph([
5,
7
]);
```
---
## Transparenz von Schnittstellen
```js
// @iserv/graph.js
export function drawGraph(data, options = {}) {
[... Implementierungsdetails]
}
// your-module.js
drawGraph([
5,
7
], {
start: 0,
stepSize: 1,
});
```
---
## Dafür hat man doch JSDoc!
```js
// @iserv/graph.js
/**
* @typedef {Object} GraphOptions
* @property {HTMLCanvasElement} mount
* @property {number} start
* @property {number} stepSize
*
* @param {GraphOptions} options
*/
export function drawGraph(data, options = {}) {
[...Implementierungsdetail]
}
// your-module.js
drawGraph(
data,
{
mount: document.getElementById('my-canvas'),
start: 2,
stepSize: 1,
},
)
```
---
## Warum nicht JSDoc?
![bg left:50% 100%](img/self-documenting.png)
* JSDoc kann lügen
* Wird nicht automatisch überprüft
---
## Typescript aufsetzen
![bg left:50% 210%](img/busy-doggo.png)
* In neuem Projekt
* Integration mit Webpack
---
## Typescript in einem neuen Projekt
Installieren
```
npm install -g typescript # global
npm install --save-dev typescript # lokal
```
---
## Typescript in einem neuen Projekt
Neues Projekt
```
tsc --init
```
* (Lokal ist der Befehl dann `npx tsc [...]`)
---
## Konfiguration
tsconfig.json
```json
{
"compilerOptions": {
"target": "es2016",
"module": "commonjs",
"esModuleInterop": true,
"forceConsistentCasingInFileNames": true,
"strict": true,
"skipLibCheck": true
}
}
```
---
## Kompilieren
```
tsc [<file>]
```
---
## Kompilieren
```ts
// index.ts
let variable: number = 5;
variable = 10;
```
<one `tsc` later>
```js
// index.js
"use strict";
let variable = 5;
variable = 10;
```
---
## Integration in Webpack-Projekten
---
## Integration in Webpack-Projekten
![bg 90%](img/webpack-typescript-bundling.png)
---
## Integration in Webpack-Projekten
```
npm install --save-dev typescript ts-loader
^^^^^^^^^
```
---
## Integration in Webpack-Projekten
```js
// webpack.config.js
module.exports = {
module: {
rules: [
{
test: /\.tsx?$/,
use: 'ts-loader',
exclude: /node_modules/,
},
],
},
resolve: {
extensions: ['.tsx', '.ts', '.js'],
},
// [...]
};
```
---
## Integration in bestehende Projekte
![bg left:50% 100%](img/typescript-integration.png)
---
## Typescript in Javascript?
* TS in JS integrieren geht ohne Probleme
* ```ts
// extension.ts
export function getFileExtension(path: string): string {
return path.split(".").slice(-1);
}
// path.js
import {getFileExtension} from './extension.ts';
console.log(getFileExtension("some/image.png"));
// > "png"
```
---
## Javascript in Typescript?
* JS in TS integrieren ist schwierig
* ```ts
// extension.js
export function getFileExtension(path) {
return path.split(".").slice(-1);
}
// path.ts
import {getFileExtension} from './extension.ts';
console.log(getFileExtension("some/image.png"));
```
---
## Javascript in Typescript
```
path.ts:1:32 - error TS7016: Could not find a declaration file
for module './extension.js'.
'./extension.js' implicitly has an 'any' type.
1 import {getFileExtension} from './extension.js';
~~~~~~~~~~~~~~~~
Found 1 error in path.ts:1
```
---
![bg 60%](img/typescript-migration-1.png)
---
![bg 60%](img/typescript-migration-2.png)
---
![bg 60%](img/typescript-migration-3.png)
---
## Javascript in Typescript
Wie damit umgehen?
* Typescript auf weniger strikt stellen
* => Nutzung von Typescript verliert an Wert
* Alle Abhängigkeiten direkt nach Typescript konvertieren
* Nicht immer machbar
* Schnittstellen mit Typen versehen
---
![bg 60%](img/typescript-migration-4.png)
---
## Schnittstellen typisieren
```ts
// extension.d.ts
export function getFileExtension(path: string): string;
```
---
## Schnittstellen typisieren
* Keine Implementierung
* Kein Type-Checking der Implementierung
* Schnittstellen werden wenigstens typisiert `¯\_(ツ)_/¯`
* Das geht auch mit JS-Libraries
---
## Welche Types gibt es?