Issue
I am trying to write a library that checks for a callback function and then calls it when it is ready. The idea being that you can include the JS asynchronously and then when it's loaded it will check for the callback and execute it.
I'm using typescript. The following JS works but wont compile in TS
if(typeof myFramework.ready === 'function') {
myFramework.ready();
}
Then the developer using the library could do the following:
var myFramework = myFramework || {}; // As the framework wont exists
myFramework.ready = function(){//Execute developer's code};
However, using TypeScript I'm getting a type error: Property 'ready' does not exist on type 'typeof myFramework' - which is not a surprise. It does compile if I do the following:
interface Window {
ready(): void;
}
if(typeof window.ready === 'function') {
window.ready();
}
But that would mean adding more crud to the window object. And I imagine calling a global ready() method could well be a point of failure!
How would you go about achieving this?
Thanks to @james-crosswell - as I have classes in separate files the file that had the Ajax handling bit in looked something like:
module MyFramework {
export interface IMyFramework {
ready? : () => any;
}
export class HasLoaded implements IMyFramework {
doReady = (framework: IMyFramework) => {
if(typeof framework.ready === 'function') {
framework.ready();
}
}
}
var newHost: HasLoaded = new HasLoaded();
newHost.doReady(MyFramework);
}
I may be rethinking the logic that got me here but that's a separate issue!
Solution
You can certainly declare/export interfaces in modules in Typescript... but they're not going to be any use to users of your framework unless those users are also using Typescript (and have the tsd for your framework).
With that caveat then, the following variant on the answer from @gilamran above worked on the Typescript Playground:
module MyModule {
export interface IMyFramework {
ready? : () => any;
}
class MyFramework implements IMyFramework {
}
class YourFramework implements IMyFramework {
ready = () => {
alert("You're ready");
}
}
export class Host {
doReady = (framework: IMyFramework) => {
if(typeof framework.ready !== 'undefined') {
framework.ready();
}
}
}
var host: Host = new Host();
host.doReady(new MyFramework());
host.doReady(new YourFramework());
}
Answered By - James Crosswell
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.