Created
June 4, 2019 19:21
-
-
Save jarhoads/06d32f831f3abfd2c2bf336e0896fa68 to your computer and use it in GitHub Desktop.
typescript interfaces
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
// Interfaces are declared with the interface keyword and | |
// contain a series of annotations to describe the contract that they represent. | |
// Interfaces do not result in any compiled JavaScript code | |
// this is due to type erasure | |
// Interfaces are used at design time to provide autocompletion and | |
// at compile time to provide type checking. | |
interface Point { | |
// Properties | |
x: number; | |
y: number; | |
} | |
interface Passenger { | |
// Properties | |
name: string; | |
} | |
interface Vehicle { | |
// Constructor | |
new(): Vehicle; | |
// Properties | |
currentLocation: Point; | |
// Methods | |
travelTo(point: Point): void; | |
addPassenger(passenger: Passenger): void; | |
removePassenger(passenger: Passenger): void; | |
} | |
// interfaces remain open and all declarations with a common root are merged into a single structure | |
// If interfaces were closed, you would be limited to the contract defined in the standard library that ships with TypeScript | |
// an additional interface block extends the built-in NodeList interface to add an onclick property that is not available natively. | |
// The implementation isn't included in this example — it may be a new web standard that has yet to find its way into TypeScript's standard library | |
// or a JavaScript library that adds the additional functionality. | |
// As far as the compiler is concerned, the interface that is defined in the standard library and | |
// the interface that is defined in your TypeScript file are one interface. | |
interface NodeList { | |
onclick: (event: MouseEvent) => any; | |
} | |
const nodeList = document.getElementsByTagName('div'); | |
nodeList.onclick = function (event: MouseEvent) { | |
alert('Clicked'); | |
}; | |
// You can also describe hybrid types with an interface, such as a function/object hybrid type | |
// Hybrid type | |
interface SimpleDocument { | |
(selector: string): HTMLElement; | |
notify(message: string): void; | |
} | |
// Implementation | |
const prepareDocument = function (): SimpleDocument { | |
let doc = <SimpleDocument>function (selector: string) { | |
return document.getElementById(selector); | |
}; | |
doc.notify = function (message: string) { | |
alert(message); | |
} | |
return doc; | |
} | |
const $ = prepareDocument(); | |
// Call $ as a function | |
const elem = $('myId'); | |
// Use $ as an object | |
$.notify(elem.id); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment