Skip to content

Instantly share code, notes, and snippets.

@abergs
Last active February 13, 2018 21:45
Show Gist options
  • Save abergs/5817818 to your computer and use it in GitHub Desktop.
Save abergs/5817818 to your computer and use it in GitHub Desktop.
Typescript Generics Example (http://ideasof.andersaberg.com/)
class MyApp {
constructor() {
var myUsers = new CustomCollection<User>();
var myMessages = new CustomCollection<Message>();
myUsers.Add(new User());
myMessages.Add(new Message());
var user: User = myUsers.GetFirst();
// Error because of generic type validation
var message: Message = myUsers.GetFirst();
// Error because of the Generic type validation.
myUsers.Add(new Message());
}
}
class User {
public Name;
}
class Message {
public Message;
}
class CustomCollection<T> {
private itemArray: Array<T>;
constructor() {
this.itemArray = [];
}
Add(item: T) {
this.itemArray.push(item);
}
GetFirst(): T {
return this.itemArray[0];
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment