-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathKitchenSink.ts
More file actions
863 lines (693 loc) · 21.4 KB
/
KitchenSink.ts
File metadata and controls
863 lines (693 loc) · 21.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
/**
* TypeScript Kitchen Sink - A comprehensive demonstration of TypeScript features
* This file showcases all major TypeScript language features and capabilities
*/
// ============================================================================
// 1. BASIC TYPES
// ============================================================================
// Primitive types
const booleanType: boolean = true;
const numberType: number = 42;
const stringType: string = "Hello TypeScript";
const bigIntType: bigint = 9007199254740991n;
const symbolType: symbol = Symbol("unique");
const undefinedType: undefined = undefined;
const nullType: null = null;
// Arrays
const numberArray: number[] = [1, 2, 3];
const stringArray: Array<string> = ["a", "b", "c"];
const readonlyArray: readonly number[] = [1, 2, 3];
const tupleType: [string, number, boolean] = ["tuple", 1, true];
const namedTuple: [first: string, second: number] = ["first", 2];
// Object types
const objectType: object = { key: "value" };
const recordType: Record<string, number> = { a: 1, b: 2 };
const indexSignature: { [key: string]: any } = { dynamic: true };
// Function types
const functionType: Function = () => {};
const arrowFunction: (x: number) => number = (x) => x * 2;
const voidFunction: () => void = () => console.log("void");
const neverFunction: () => never = () => { throw new Error("never returns"); };
// ============================================================================
// 2. UNION AND INTERSECTION TYPES
// ============================================================================
// Union types
type StringOrNumber = string | number;
let unionVariable: StringOrNumber = "text";
unionVariable = 42;
// Intersection types
type Named = { name: string };
type Aged = { age: number };
type Person = Named & Aged;
const person: Person = { name: "Alice", age: 30 };
// Discriminated unions
type Square = { kind: "square"; size: number };
type Rectangle = { kind: "rectangle"; width: number; height: number };
type Circle = { kind: "circle"; radius: number };
type Shape = Square | Rectangle | Circle;
function getArea(shape: Shape): number {
switch (shape.kind) {
case "square": return shape.size ** 2;
case "rectangle": return shape.width * shape.height;
case "circle": return Math.PI * shape.radius ** 2;
}
}
// ============================================================================
// 3. LITERAL TYPES
// ============================================================================
// String literals
type Direction = "north" | "south" | "east" | "west";
const direction: Direction = "north";
// Numeric literals
type DiceRoll = 1 | 2 | 3 | 4 | 5 | 6;
const roll: DiceRoll = 6;
// Boolean literals
type True = true;
type False = false;
// Template literal types
type Greeting = `Hello ${string}`;
type ColorShade = `${"light" | "dark"}-${"red" | "blue" | "green"}`;
const shade: ColorShade = "light-blue";
// ============================================================================
// 4. TYPE ALIASES AND INTERFACES
// ============================================================================
// Type aliases
type ID = string | number;
type Point2D = { x: number; y: number };
type Point3D = Point2D & { z: number };
// Interfaces
interface IUser {
id: ID;
name: string;
email?: string; // Optional property
readonly createdAt: Date; // Readonly property
}
// Interface extension
interface IEmployee extends IUser {
department: string;
salary: number;
}
// Interface merging
interface Window {
customProperty: string;
}
// Hybrid types
interface Counter {
(start: number): string;
interval: number;
reset(): void;
}
// ============================================================================
// 5. GENERICS
// ============================================================================
// Generic functions
function identity<T>(arg: T): T {
return arg;
}
// Generic constraints
function getProperty<T, K extends keyof T>(obj: T, key: K): T[K] {
return obj[key];
}
// Generic interfaces
interface Box<T> {
value: T;
}
// Generic classes
class GenericClass<T> {
private value: T;
constructor(value: T) {
this.value = value;
}
getValue(): T {
return this.value;
}
}
// Generic type aliases
type Result<T, E = Error> =
| { success: true; value: T }
| { success: false; error: E };
// Generic utility types usage
type Partial<T> = { [P in keyof T]?: T[P] };
type Required<T> = { [P in keyof T]-?: T[P] };
type Readonly<T> = { readonly [P in keyof T]: T[P] };
// ============================================================================
// 6. CLASSES
// ============================================================================
// Basic class
class Animal {
name: string;
constructor(name: string) {
this.name = name;
}
move(distance: number = 0): void {
console.log(`${this.name} moved ${distance}m`);
}
}
// Inheritance
class Dog extends Animal {
breed: string;
constructor(name: string, breed: string) {
super(name);
this.breed = breed;
}
bark(): void {
console.log("Woof!");
}
}
// Access modifiers
class Car {
public brand: string;
private engineCode: string;
protected mileage: number;
readonly vin: string;
constructor(brand: string, engineCode: string, vin: string) {
this.brand = brand;
this.engineCode = engineCode;
this.mileage = 0;
this.vin = vin;
}
}
// Abstract classes
abstract class Shape2D {
abstract getArea(): number;
abstract getPerimeter(): number;
describe(): string {
return `Area: ${this.getArea()}, Perimeter: ${this.getPerimeter()}`;
}
}
class Rectangle2D extends Shape2D {
constructor(private width: number, private height: number) {
super();
}
getArea(): number {
return this.width * this.height;
}
getPerimeter(): number {
return 2 * (this.width + this.height);
}
}
// Static members
class MathUtils {
static PI = 3.14159;
static calculateCircleArea(radius: number): number {
return this.PI * radius * radius;
}
}
// Parameter properties
class Point {
constructor(
public x: number,
public y: number,
private z: number = 0
) {}
}
// Getters and setters
class Temperature {
private _celsius: number = 0;
get celsius(): number {
return this._celsius;
}
set celsius(value: number) {
if (value < -273.15) {
throw new Error("Temperature below absolute zero is not possible");
}
this._celsius = value;
}
get fahrenheit(): number {
return (this._celsius * 9/5) + 32;
}
set fahrenheit(value: number) {
this.celsius = (value - 32) * 5/9;
}
}
// ============================================================================
// 7. ENUMS
// ============================================================================
// Numeric enum
enum Status {
Pending,
Active,
Completed,
Cancelled = 10,
Archived
}
// String enum
enum Color {
Red = "RED",
Green = "GREEN",
Blue = "BLUE"
}
// Heterogeneous enum
enum Mixed {
No = 0,
Yes = "YES"
}
// Const enum
const enum FileAccess {
None,
Read = 1 << 1,
Write = 1 << 2,
ReadWrite = Read | Write
}
// ============================================================================
// 8. ADVANCED TYPES
// ============================================================================
// Type guards
function isString(value: unknown): value is string {
return typeof value === "string";
}
// Type predicates with classes
class Bird {
fly() { console.log("Flying"); }
}
class Fish {
swim() { console.log("Swimming"); }
}
function isBird(pet: Bird | Fish): pet is Bird {
return (pet as Bird).fly !== undefined;
}
// Typeof type guards
function processValue(value: string | number) {
if (typeof value === "string") {
return value.toUpperCase();
} else {
return value.toFixed(2);
}
}
// Instanceof type guards
function processDate(value: Date | string) {
if (value instanceof Date) {
return value.getTime();
} else {
return Date.parse(value);
}
}
// Conditional types
type IsString<T> = T extends string ? true : false;
type ExtractArrayType<T> = T extends (infer U)[] ? U : never;
// Mapped types
type Nullable<T> = { [K in keyof T]: T[K] | null };
type DeepReadonly<T> = {
readonly [P in keyof T]: T[P] extends object ? DeepReadonly<T[P]> : T[P];
};
// Key remapping in mapped types
type Getters<T> = {
[K in keyof T as `get${Capitalize<string & K>}`]: () => T[K];
};
// Index access types
type PersonName = Person["name"];
type PersonKeys = keyof Person;
// ============================================================================
// 9. UTILITY TYPES
// ============================================================================
interface Todo {
title: string;
description: string;
completed: boolean;
createdAt: Date;
}
// Partial
type PartialTodo = Partial<Todo>;
// Required
type RequiredTodo = Required<PartialTodo>;
// Readonly
type ReadonlyTodo = Readonly<Todo>;
// Pick
type TodoPreview = Pick<Todo, "title" | "completed">;
// Omit
type TodoInfo = Omit<Todo, "completed" | "createdAt">;
// Record
type PageInfo = Record<"home" | "about" | "contact", { title: string }>;
// Exclude
type T0 = Exclude<"a" | "b" | "c", "a">; // "b" | "c"
// Extract
type T1 = Extract<"a" | "b" | "c", "a" | "f">; // "a"
// NonNullable
type T2 = NonNullable<string | number | undefined | null>; // string | number
// Parameters
type T3 = Parameters<(s: string, n: number) => void>; // [string, number]
// ReturnType
type T4 = ReturnType<() => string>; // string
// ConstructorParameters
type T5 = ConstructorParameters<typeof Date>; // [value: string | number | Date]
// InstanceType
type T6 = InstanceType<typeof Date>; // Date
// ThisParameterType
function toHex(this: Number) {
return this.toString(16);
}
type T7 = ThisParameterType<typeof toHex>; // Number
// OmitThisParameter
type T8 = OmitThisParameter<typeof toHex>; // () => string
// ThisType
type ObjectDescriptor<D, M> = {
data?: D;
methods?: M & ThisType<D & M>;
};
// Awaited
type T9 = Awaited<Promise<string>>; // string
// ============================================================================
// 10. MODULES AND NAMESPACES
// ============================================================================
// Namespace
namespace Validation {
export interface StringValidator {
isAcceptable(s: string): boolean;
}
export class ZipCodeValidator implements StringValidator {
isAcceptable(s: string) {
return s.length === 5;
}
}
}
// Module augmentation
declare module "./KitchenSink" {
interface ExportedInterface {
newProperty: string;
}
}
// Global augmentation
declare global {
interface Array<T> {
customMethod(): void;
}
}
// ============================================================================
// 11. DECORATORS (Experimental)
// ============================================================================
// Class decorator
function sealed(constructor: Function) {
Object.seal(constructor);
Object.seal(constructor.prototype);
}
// Method decorator
function enumerable(value: boolean) {
return function (target: any, propertyKey: string, descriptor: PropertyDescriptor) {
descriptor.enumerable = value;
};
}
// Property decorator
function format(formatString: string) {
return function (target: any, propertyKey: string): void {
// Property decorator logic
};
}
// Parameter decorator
function required(target: any, propertyKey: string | symbol, parameterIndex: number) {
// Parameter decorator logic
}
@sealed
class BugReport {
@format("Hello, %s")
title: string;
constructor(title: string) {
this.title = title;
}
@enumerable(false)
print(@required verbose: boolean) {
console.log(this.title);
}
}
// ============================================================================
// 12. ADVANCED FUNCTION FEATURES
// ============================================================================
// Function overloading
function processInput(x: string): string;
function processInput(x: number): number;
function processInput(x: string | number): string | number {
if (typeof x === "string") {
return x.toUpperCase();
} else {
return x * 2;
}
}
// Rest parameters
function sum(...numbers: number[]): number {
return numbers.reduce((a, b) => a + b, 0);
}
// This parameters
interface UIElement {
addClickListener(onclick: (this: void, e: Event) => void): void;
}
// Function type expressions
type GreetFunction = (name: string) => string;
const greet: GreetFunction = (name) => `Hello, ${name}!`;
// Call signatures
type DescribableFunction = {
description: string;
(someArg: number): boolean;
};
// Construct signatures
type SomeConstructor = {
new (s: string): object;
};
// ============================================================================
// 13. ASSERTION FUNCTIONS AND TYPE NARROWING
// ============================================================================
// Type assertions
const someValue: unknown = "this is a string";
const strLength1 = (someValue as string).length;
const strLength2 = (<string>someValue).length;
// Const assertions
const CONFIG = {
endpoint: "https://api.example.com",
timeout: 3000
} as const;
// Type narrowing with in operator
type Car2 = { drive(): void };
type Boat = { sail(): void };
function move(vehicle: Car2 | Boat) {
if ("drive" in vehicle) {
vehicle.drive();
} else {
vehicle.sail();
}
}
// Exhaustiveness checking
function assertNever(x: never): never {
throw new Error("Unexpected object: " + x);
}
function handleShape(shape: Shape) {
switch (shape.kind) {
case "square":
return shape.size ** 2;
case "rectangle":
return shape.width * shape.height;
case "circle":
return Math.PI * shape.radius ** 2;
default:
return assertNever(shape);
}
}
// ============================================================================
// 14. SYMBOLS AND ITERATORS
// ============================================================================
// Unique symbols
const sym1 = Symbol("key");
const sym2 = Symbol("key");
// Symbol as property keys
const symbolKey = Symbol("myProperty");
const objWithSymbol = {
[symbolKey]: "value"
};
// Well-known symbols
class IterableClass implements Iterable<number> {
private data: number[] = [1, 2, 3];
[Symbol.iterator](): Iterator<number> {
let index = 0;
const data = this.data;
return {
next(): IteratorResult<number> {
if (index < data.length) {
return { value: data[index++], done: false };
} else {
return { value: undefined as any, done: true };
}
}
};
}
}
// ============================================================================
// 15. ASYNC PATTERNS
// ============================================================================
// Promises
function fetchData(): Promise<string> {
return new Promise((resolve, reject) => {
setTimeout(() => resolve("Data"), 1000);
});
}
// Async/await
async function processAsync(): Promise<void> {
try {
const data = await fetchData();
console.log(data);
} catch (error) {
console.error(error);
}
}
// Async generators
async function* asyncGenerator(): AsyncGenerator<number> {
let i = 0;
while (i < 3) {
yield await Promise.resolve(i++);
}
}
// Promise utility types
type PromiseType<T> = T extends Promise<infer U> ? U : never;
// ============================================================================
// 16. MIXINS
// ============================================================================
// Mixin pattern
type Constructor<T = {}> = new (...args: any[]) => T;
function Timestamped<TBase extends Constructor>(Base: TBase) {
return class extends Base {
timestamp = Date.now();
};
}
function Activatable<TBase extends Constructor>(Base: TBase) {
return class extends Base {
isActive = false;
activate() {
this.isActive = true;
}
deactivate() {
this.isActive = false;
}
};
}
class User {
constructor(public name: string) {}
}
const TimestampedActivatableUser = Timestamped(Activatable(User));
const user = new TimestampedActivatableUser("John");
// ============================================================================
// 17. TRIPLE-SLASH DIRECTIVES
// ============================================================================
/// <reference path="types.d.ts" />
/// <reference types="node" />
/// <reference lib="es2020.string" />
// ============================================================================
// 18. TYPE MANIPULATION
// ============================================================================
// keyof operator
type PersonKeys2 = keyof Person;
// typeof operator
const person2 = { name: "Alice", age: 30 };
type PersonType = typeof person2;
// Indexed access types
type Age = Person["age"];
// Template literal types
type EventName<T extends string> = `${T}Changed`;
type PropEventName = EventName<"prop">; // "propChanged"
// Intrinsic string manipulation types
type Uppercase<S extends string> = intrinsic;
type Lowercase<S extends string> = intrinsic;
type Capitalize<S extends string> = intrinsic;
type Uncapitalize<S extends string> = intrinsic;
// ============================================================================
// 19. VARIANCE
// ============================================================================
// Covariance (for outputs)
interface Producer<T> {
produce(): T;
}
// Contravariance (for inputs)
interface Consumer<T> {
consume(item: T): void;
}
// Invariance (for both input and output)
interface Storage<T> {
get(): T;
set(item: T): void;
}
// Bivariance (TypeScript's default for methods)
interface BivariantMethod<T> {
method(x: T): T;
}
// ============================================================================
// 20. PATTERN MATCHING AND DESTRUCTURING
// ============================================================================
// Object destructuring with types
const { name: userName, age: userAge }: { name: string; age: number } = person;
// Array destructuring with types
const [first, second]: [string, number] = ["one", 2];
// Rest patterns
const [head, ...tail]: number[] = [1, 2, 3, 4, 5];
const { id, ...rest }: { id: number; name: string; email: string } = {
id: 1,
name: "Alice",
email: "alice@example.com"
};
// Destructuring in function parameters
function printPerson({ name, age }: { name: string; age: number }): void {
console.log(`${name} is ${age} years old`);
}
// ============================================================================
// 21. SATISFIES OPERATOR
// ============================================================================
type Colors = "red" | "green" | "blue";
type RGB = [red: number, green: number, blue: number];
const palette = {
red: [255, 0, 0],
green: "#00ff00",
blue: [0, 0, 255]
} satisfies Record<Colors, string | RGB>;
// ============================================================================
// 22. CONST TYPE PARAMETERS
// ============================================================================
function constTypeParam<const T>(arg: T): T {
return arg;
}
const result = constTypeParam({ x: 10, y: 20 }); // Type is { x: 10; y: 20 }
// ============================================================================
// 23. USING DECLARATIONS (TypeScript 5.2+)
// ============================================================================
class DisposableResource {
[Symbol.dispose]() {
console.log("Resource disposed");
}
}
async function useResource() {
using resource = new DisposableResource();
// Resource will be automatically disposed when scope ends
}
// ============================================================================
// 24. EXPORT AND IMPORT PATTERNS
// ============================================================================
// Named exports
export interface ExportedInterface {
prop: string;
}
export class ExportedClass {
method() {}
}
export const exportedConst = "value";
// Default export
export default class DefaultClass {
defaultMethod() {}
}
// Type-only imports/exports
export type { Person };
import type { SomeType } from "./types";
// Namespace exports
export * as Utils from "./utils";
// Re-exports
export { Animal, Dog } from "./KitchenSink";
// ============================================================================
// 25. DECLARATION MERGING
// ============================================================================
interface MergedInterface {
prop1: string;
}
interface MergedInterface {
prop2: number;
}
// Both properties are available
const merged: MergedInterface = {
prop1: "text",
prop2: 42
};
// ============================================================================
// END OF KITCHEN SINK
// ============================================================================
console.log("TypeScript Kitchen Sink loaded successfully!");