Gion Kunz
Let's create together.
by Gion Kunz
Founder, UI Developer, UX Enthusiast at syncrea GmbH
type FibonacciNumber = 1 | 2 | 3 | 5 | 8 | 13;
// Error!
const n: FibonacciNumber = 4;
type OrderStatus = 'Ordered' | 'Paid' | 'Shipped' | 'Delivered';
interface Order {
id: number;
status: OrderStatus;
}
const order: Order = {
id: 1,
status: 'Ordered'
};
interface Cat {
name: string;
meow: () => void;
}
interface Dog {
name: string;
bark: () => void;
}
export type CatDog = Cat & Dog;
export interface Apple {
readonly kind: 'Apple';
readonly color: string;
}
export interface Banana {
readonly kind: 'Banana';
readonly bendRadius: number;
}
export type Fruit = Apple | Banana;
export interface Person {
readonly firstName: string;
readonly lastName: string;
}
const person: Person = {
firstName: 'Peter',
lastName: 'Griffin'
};
export class DesigningDeveloper {
design(): void {
// Can design
}
develop(): void {
// Can develop
}
}
Example: Create a graphics application with Shapes that can be rendered, manipulated, grouped etc.
// Factory function that creates a logger function with a specified prefix
const createLogger = (prefix: string): ((message: string) => void) => {
return (message: string) => {
console.log(`${prefix}: ${message}`);
};
};
// Usage
const infoLogger = createLogger('INFO');
const errorLogger = createLogger('ERROR');
infoLogger('This is an info message.');
// Output: INFO: This is an info message.
errorLogger('This is an error message.');
// Output: ERROR: This is an error message.
const getMax = <T>(
arr: T[],
compare: (a: T, b: T) => number): T | undefined => {
if (arr.length === 0) return undefined;
return arr.reduce((max, item) => (compare(max, item) > 0 ? max : item));
};
const numberCompare = (a: number, b: number): number => a - b;
// Usage
const numbers = [3, 1, 4, 1, 5, 9];
const maxNumber = getMax(numbers, numberCompare);
console.log(maxNumber); // Output: 9
type Show<T> = { show: (item: T) => string; };
const showRegistry: Record<string, Show<any>> = {};
// Register Show implementations
showRegistry['string'] = { show: (item: string) => `String: ${item}` };
showRegistry['number'] = { show: (item: number) => `Number: ${item}` };
const showItem = (type: string, item: any): string =>
showRegistry[type]?.show?.(item);
console.log(showItem('string', 'Hello')); // Output: String: Hello
console.log(showItem('number', 42)); // Output: Number: 42
By Gion Kunz
The ugly truth about Class-based Object Oriented Programming and Encapsulation