I am currently writing a *d.ts files for a private JavaScript file that I cannot modify. I'm currently trying to define a property in an interface that can be either a string or a function:
var obj = {
href: function(data) { return "/page/" + data.id; }
}
OR
var obj = {
href: "page/list.html"
}
After looking at the typescript doc about interfaces I came across the follow example but it won't let me define the function as an optional type as shown below:
interface IObj {
href: {
(...any)?: any;
string? ;
};
}
Is this even possible? Or am I approaching this the wrong way?
What you are really looking for is a Union
Type (denoted by |
). For your case:
interface IObj {
href: string | { (...any): any };
};
var obj: IObj = {
href: "page/list.html"
}
var obj: IObj = {
href: function (data) { return "/page/" + data.id; }
}
// ERROR
var obj: IObj = {
href: 123
}
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments