Skip to content

Instantly share code, notes, and snippets.

@elyosemite
Created April 28, 2018 00:18
Show Gist options
  • Select an option

  • Save elyosemite/c17e3ed3171342f86031e039d437d854 to your computer and use it in GitHub Desktop.

Select an option

Save elyosemite/c17e3ed3171342f86031e039d437d854 to your computer and use it in GitHub Desktop.
interface ClockConstructor {
new (hour: number, minute: number);
}
interface ClockInterface {
tick();
}
function createClock(ctor: ClockConstructor, hour: number, minute: number): ClockInterface {
return new ctor(hour, minute);
}
class DigitalClock implements ClockInterface {
constructor(h: number, m: number) { }
tick() {
console.log("beep beep");
}
}
class AnalogClock implements ClockInterface {
constructor(h: number, m: number) { }
tick() {
console.log("tick tock");
}
}
let digital = createClock(DigitalClock, 12, 17);
let analog = createClock(AnalogClock, 7, 32);
@elyosemite
Copy link
Author

I've taken this example of the doc (link bellow).
I didn't understand how this elements (functions and interfaces) relate to each other.

  • Why createClock's first parameter is of the type ClockConstructor, but we pass one class that implements other interface's type, that's ClockInterface? I expected, at least, one type that implement ClockConstructor. How it works?

http://www.typescriptlang.org/docs/handbook/interfaces.html

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment