wiki/content/20200929163051-typescript_generics.md

61 lines
1.1 KiB
Markdown
Raw Normal View History

2024-05-06 20:40:05 +00:00
---
2024-10-29 18:27:12 +00:00
date: 2020-09-29
2024-05-06 20:40:05 +00:00
id: aacdac15-4e00-4d75-9888-79b23bb47498
title: TypeScript Generics
---
# Examples
## Function level
``` typescript
function reverse<T>(items: T[]): T[] {
var toreturn = [];
for (let i = items.length - 1; i >= 0; i--) {
toreturn.push(items[i]);
}
return toreturn;
}
var sample = [1, 2, 3];
var reversed = reverse(sample);
console.log(reversed); // 3,2,1
// Safety!
reversed[0] = '1'; // Error!
reversed = ['1', '2']; // Error!
reversed[0] = 1; // Okay
reversed = [1, 2]; // Okay
```
## Class level
``` typescript
/** A class definition with a generic parameter */
class Queue<T> {
private data = [];
push(item: T) { this.data.push(item); }
pop(): T | undefined { return this.data.shift(); }
}
/** Again sample usage */
const queue = new Queue<number>();
queue.push(0);
queue.push("1"); // ERROR : cannot push a string. Only numbers allowed
```
## Member functions
``` typescript
class Utility {
reverse<T>(items: T[]): T[] {
var toreturn = [];
for (let i = items.length - 1; i >= 0; i--) {
toreturn.push(items[i]);
}
return toreturn;
}
}
```