Als Fullstackentwickler ist man mit einem bunten Blumenstrauß an Technologien gesegnet. Insbesondere JavaScript und TypeScript ist für viele Java Entwickler erst einmal ungewohntes Terrain. Diese kleine Serie zeigt zumindest einige Features über die der ein oder andere Java Entwickler sicherlich den Kopf schütteln wird (bis er sie lieben gelernt hat 🙂 )
JavaScript kennt bekanntlich keine statische Typisierung, TypeScript fügt diese zumindest zur Compile-Zeit hinzu, ist aber dennoch recht „flexibel“, was diese angeht: Union Types
interface Message {
msg: string
}
function helloWorld(message: Message | string | number | string[] | number[]) {
// impl
}
helloWorld({msg: "I am no Message, but have a msg-Attribute"})
helloWorld("Hello");
helloWorld(["Hello", "World"]);
helloWorld(12);
helloWorld([12, 13]);
Am Ende ist alles true oder false, zumindest wenn wir das wollen: Truthiness
let emptyValue;
const value = "Hello World";
const message: Message = {msg: "Hello World"}
const no0= 0;
const no1 = 1;
if (value || message) {
//...
}
console.log(!!emptyValue) // false
console.log(!!value) // true
console.log(!!message) // true
console.log(!!no0) // false
console.log(!!no1) // true
console.log(!!!no1) // false
Flexibilität ist alles, auch bei der Deklaration von Methoden: default- und optional – parameter
// ### default and optional parameter
function sendMessage(message:string, title = 'New Message', author? : string){
console.log(message, title, author);
}
sendMessage('Hello Word')
sendMessage('Hello World', 'World-Message')
sendMessage('Hello World', 'World-Message', 'Dominik Mathmann')
sendMessage('Hello World', undefined, 'Dominik Mathmann')
Typisierung ist prima. Auch wenn es um Funktionen geht: call signatures
function loadData(query: string, callback: (_: string[]) => void) {
//...
callback([]);
}
loadData("...", (data) => console.log(data));