File tree Expand file tree Collapse file tree 1 file changed +57
-0
lines changed
tests/syntax-tests/source/Markdown Expand file tree Collapse file tree 1 file changed +57
-0
lines changed Original file line number Diff line number Diff line change 1+ # Typescript test
2+
3+ ``` typescript
4+ enum Status {
5+ Pending ,
6+ InProgress ,
7+ Completed ,
8+ }
9+
10+ interface Task {
11+ id: number ;
12+ title: string ;
13+ status: Status ;
14+ assignee? : string ;
15+ }
16+
17+ class TaskManager <T extends Task > {
18+ private tasks: T [] = [];
19+
20+ addTask(task : T ): void {
21+ this .tasks .push (task );
22+ }
23+
24+ getTasksByStatus(status : Status ): T [] {
25+ return this .tasks .filter (task => task .status === status );
26+ }
27+
28+ async fetchTasks(): Promise <T []> {
29+ // Simulate async fetch
30+ return new Promise (resolve => setTimeout (() => resolve (this .tasks ), 500 ));
31+ }
32+ }
33+
34+ // Type guard
35+ function isTask(obj : any ): obj is Task {
36+ return typeof obj .id === ' number' && typeof obj .title === ' string' ;
37+ }
38+
39+ // Usage
40+ const manager = new TaskManager <Task >();
41+ manager .addTask ({ id: 1 , title: " Write docs" , status: Status .Pending });
42+ manager .addTask ({ id: 2 , title: " Review PR" , status: Status .InProgress , assignee: " Alice" });
43+
44+ (async () => {
45+ const allTasks = await manager .fetchTasks ();
46+ allTasks .forEach (task => {
47+ if (isTask (task )) {
48+ console .log (` Task #${task .id }: ${task .title } [${Status [task .status ]}] ` );
49+ }
50+ });
51+ })();
52+
53+ // Type assertion
54+ const unknownValue: unknown = { id: 3 , title: " Test" , status: Status .Completed };
55+ const assertedTask = unknownValue as Task ;
56+ console .log (assertedTask .title );
57+ ```
You can’t perform that action at this time.
0 commit comments