How would you use TypeScript to improve the type-ahead and type checking for JQueryUI function calls

StackOverflow https://stackoverflow.com//questions/12679888

  •  12-12-2019
  •  | 
  •  

Question

When working with a jQuery UI widget, you often end up with something that follows this pattern:

$("#someId").someWidget("option", "someOption", value);

Is there a good way to model this interaction to get some useful type checking out of TypeScript? Technically you probably have the method defined like this:

someWidget(optionLiteral: string, optionName: string, optionValue: any): JQuery;

(Modeled after the provided jQuery UI type definitions)

So option value is basically "any" no matter the option name. Is there a way to overload the type definition further and maybe do some pattern matching on optionName? Or are there any plans for this?

Was it helpful?

Solution

You might want to dig into the jQuery UI example,

http://www.typescriptlang.org/Samples/#Warship

which covers how to extend the jQuery interface type with additional methods.

The jQuery type is an interface type and interface types are open in TypeScript, meaning that later compilation units can add members to the type. Your example would be written like,

interface JQuery {
    someWidget(optionLiteral: string, optionName: string, optionValue: any): JQuery
}

As for overloading, methods can be overloaded on type but not value. Overloading on values would make a good suggestion on the CodePlex site.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top