capypad
0 Tage Serie
typescript / expert
Snippet

Assertion-Signaturen für Runtime-Guarding

Assertion-Signaturen verwenden das 'asserts'-Schlüsselwort, um dem Compiler mitzuteilen, dass eine Bedingung wahr sein muss, wenn die Funktion normal zurückkehrt. Dies schränkt Typen für den Rest des Scopes ein und reduziert verschachtelte If-Blöcke.

snippet.ts
typescript
1
2
3
4
5
6
7
8
9
10
11
function assertIsString(val: any): asserts val is string {
if (typeof val !== "string") {
throw new Error("Not a string!");
}
}
 
function process(input: unknown) {
assertIsString(input);
// input is now narrowed to 'string' for the rest of the scope
console.log(input.toUpperCase());
}
Erklärung
1
asserts val is string
Die Signatur, die angibt, dass die Funktion den Parameter 'val' bei erfolgreicher Ausführung einschränkt.
2
input.toUpperCase()
Erlaubt, da der Compiler weiß, dass 'input' nach dem Assertion-Aufruf ein String sein muss.