Argument of type 'string' is not assignable to parameter of type '{ [key:string]:any;}

Question!

I am getting the following error on typescript file when I try to attach a click event handler as shown below,

Argument of type 'string' is not assignable to parameter of type '{ [key:string]:any;}

enter image description here

I have jQuery 2.1.4 and jquery.TypeScript.DefinitelyTyped 3.0.4 configured in my ASP.NET Web Application.

Edit:

My typescript file is able to pickup the definition file as shown below,

enter image description here

in my JQuery.d.ts,I see the following overloads,

on(events: string, handler: (eventObject: JQueryEventObject, ...args: any[]) => any): JQuery;
on(events: string, data : any, handler: (eventObject: JQueryEventObject, ...args: any[]) => any): JQuery;
on(events: string, selector: string, handler: (eventObject: JQueryEventObject, ...eventData: any[]) => any): JQuery;
on(events: string, selector: string, data: any, handler: (eventObject: JQueryEventObject, ...eventData: any[]) => any): JQuery;
on(events: { [key: string]: any; }, selector?: string, data?: any): JQuery;
on(events: { [key: string]: any; }, data?: any): JQuery;

What am I missing? Any suggestion will be greatly appreciated.



Answers

According to the jquery.d.ts the following typings are available for the on function:

1. on(events: string, selector: string, handler: (eventObject: JQueryEventObject, ...eventData: any[]) => any): JQuery;
2. on(events: string, selector: string, data: any, handler: (eventObject: JQueryEventObject, ...eventData: any[]) => any): JQuery;
3. on(events: { [key: string]: any; }, selector?: string, data?: any): JQuery;
4. on(events: { [key: string]: any; }, data?: any): JQuery;

Now since you are implementing the function the following way

$(this.elementId).on("click", changeEventHandler)

Either the 3rd or the 4th typing of on will get applied, which require the first element to be of type { [key: string]: any; }. What you need to do is provide a selector to which the click function needs to be applied. So here are your options:

$(this.elementId).click(changeEventHandler)
OR
$(document).on("click", this.elementId, changeEventHandler)

The thing that you were missing is that when using the on function along with the event type and the event handler you also need to specify the DOMElement on which the listener is to be attached



jquery.TypeScript.DefinitelyTyped 3.0.

Please stop using nuget for TypeScript type definitions.

Best solution:

Just download and include this file in your project : https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/jquery/jquery.d.ts

More

  • Check that you are on TypeScript latest
By : basarat


This video can help you solving your question :)
By: admin