Suppose I have the following third party JavaScript function that I want to call from TypeScript:
function foo(obj) {
var x = new obj.newable();
x.bar();
}
Here is what my JavaScript code (which I want to port to typescript) does:
foo({
newable: function() {
this.bar = function() {
console.log("Hi");
}
}
});
This successfully prints "hi". But now I want to port my code to TypeScript. Especially I want to make sure that the object returned by new obj.newable()
contains a method bar
.
I tried some things like:
interface IForFoo {
newable: {new () : IWithBar};
}
interface IWithBar {
bar: () => void;
}
function foo(obj: IForFoo) { // this will eventually be specified in a .t.ts file
var x = new obj.newable();
x.bar();
}
but that does not work, because Type 'new() => IWithBar' requires a construct signature, but type '() => void' lacks one
. (To be honest I haven't figured out what exactly a construct signature
refers to).
How do I get this "right"?
First lets get it to work.
The following works and is the simplest solution
interface Foo{
newable:{
() : {bar:Function}
}
}
declare function foo(arg:Foo);
foo({
newable: function() {
this.bar = function() {
console.log("Hi");
}
return this;
}
});
If you want to enforce the newable constraint i.e it MUST accomodate for new
you need to use a TypeScript class i.e.
interface Foo {
newable: {
new (): { bar: Function }
}
}
declare function foo(arg: Foo);
class NewAble {
bar = () => console.log('Hi');
}
foo({
newable: NewAble
});
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments