Last active
February 13, 2018 21:45
-
-
Save abergs/5817818 to your computer and use it in GitHub Desktop.
Typescript Generics Example (http://ideasof.andersaberg.com/)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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