Typescript: Die Datentypen any, unknown und never

in deutsch •  7 months ago 

Wenn ihr Typescript verwendet, dann werdet ihr wahrscheinlich früher oder später auf die Datentypen any, unknown und never stoßen.
Zum Beispiel wenn man eine Javascript Bibliothek nutzt, dann wird öfters any und unknown vorgeschlagen. Oder wenn man Javascript code in Typescript code umwandeltn möchte, dann hagelt es voller anys in den Vorschlägen.
Doch was ist der Unterschied zwischen any, unknown und never?
Any kann alles sein ohne Typsicherheit, so wie im original Javascript. Unknown verlangt eine Typsicherheit, kann aber auch alles sein. Never stellt sicher, dass eine Funktion nichts zurückgibt.

Hier ein kurzes Beispiel:

/* use 'any' if you convert JS into TS. Or when type safety is not needed for this context */
let content: any = 4;
content = true;
content = [1,2,3,4,5];
console.log(content);

/* use 'unknown' if you want to ensure type safety in TS */
let no_idea: unknown = 4;
no_idea = '   unknown text   ';

/* some compilers say 'no_idea' is of type 'unknown' if you execute the next line */
no_idea = no_idea.trim();

/* to avoid this error make sure that 'unknown' is type of string before use a string function */
if(typeof no_idea === 'string'){
    no_idea = no_idea.trim();
    console.log(no_idea);
}

/* use 'never' for functions that ensure to return nothing*/
function neverFunction(text: string): never {
   throw new Error(text);
}

neverFunction("never test");

Authors get paid when people like you upvote their post.
If you enjoyed what you read here, create your account today and start earning FREE BLURT!
Sort Order:  
  ·  7 months ago  ·  

image

Hi @ozelot47, great news! Your content was selected by curators @ten-years-before, @nalexadre to receive a special curation from BeBlurt 🎉 Don't hesitate to upvote this comment as the curators will receive 80% of the rewards for their involvement.

You can support us by voting for our witness, our decentralized funding proposal, or through delegation. You're also welcome to join our Discord server 👉 https://discord.beblurt.com

image
*For a delegation of 45,000 BLURT 👉 https://beblurt.com/mydelegation/@beblurt

image
BeBlurt (Blurt frontend) 👉 https://beblurt.com
on IOS/Android 👉 https://beblurt.com/s/aMGBrg