Created
March 29, 2018 14:35
-
-
Save leohxj/f524a4f3e96b727b291352805869e80f to your computer and use it in GitHub Desktop.
typescript duck typing
This file contains hidden or 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
| interface IItem | |
| { | |
| id: number, | |
| title: string | |
| }; | |
| function print(item: IItem) | |
| { | |
| console.log(item.id + " > " + item.title); | |
| } | |
| var i : IItem = { | |
| id: 10, | |
| title : "ABC" | |
| }; | |
| //Ok - As it implements IItem | |
| print(i); | |
| //Ok - As it implicitly implements IItem | |
| print({ id: 11, title: "XYZ"}); | |
| interface IProduct | |
| { | |
| id: number, | |
| title: string, | |
| author: string | |
| }; | |
| var book: IProduct = { | |
| id: 1, | |
| title: "C# in Depth", | |
| author: "Jon Skeet" | |
| }; | |
| //Ok - Even though book implements IProduct and not the IItem | |
| //It has two properties "id" and "title" | |
| //which is actually the print function is interested in | |
| print(book); | |
| print({ | |
| id: 2, | |
| title: 'fuck', | |
| author: 'leo' | |
| }) | |
| var x = { | |
| id: 3, | |
| title: "fuck again", | |
| author: 'leo' | |
| } | |
| print(x) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment