1

I am using TypeScript to generate some DOM element from a templated string. Now I know that in plain old javascript + JQuery you can do: var domObj = $(myString) or to make it more evident: var comObj = $('<div></div>'); and it works just like that.

I've been trying to do the same with TS and I always get some error telling me it can't say which overload to use.

Is there any other way to do what I'm trying to do? Can it be done in TS?

Edit:

The issue I'm facing is not how to use JQuery from TypeScript is about a specific feature I want to load a string variable to a JQuery object, I know it can be done in plain old js but I get overloading errors when doing so.

Unlike this question which asks how to use JQuery from ts, which I have mostly figured out except for that little details I have just mentioned

Community
  • 1
  • 1
Luiso
  • 4,173
  • 2
  • 37
  • 60
  • 1
    Possible duplicate of [How to use jQuery with TypeScript](http://stackoverflow.com/questions/32050645/how-to-use-jquery-with-typescript) – JJJ Jan 30 '17 at 17:41
  • 2
    @JJJ I already have `jquery.d.ts` and everything else works fine, it loading the `string` as a `JQuery` that's causing me trouble. – Luiso Jan 30 '17 at 17:43
  • 1
    @JoshCrozier yes it does, thank you very much. if you could please add that as an answer and elaborate/explain it a little more I'd more than happy to mark it accepted. – Luiso Jan 30 '17 at 17:50

1 Answers1

1

Based on my comment above, you need to use a type assertion in order to avoid that error.

The most versatile option would be to use the any type since that will prevent typing errors from being thrown:

var comObj = ($('<div></div>') as any);

// or

var comObj = (<any>$('<div></div>'));

// or

var comObj: any = $('<div></div>');

Without seeing the full code, it's hard to know what exactly was happening in your case.

However, without context, it seems like the problem is that the compiler thinks that you are passing a string that represents a CSS selector, but in reality you were passing in stringified HTML, which results in the error that you are seeing.


As a side note, here is a relevant snippet in the TypeScript documentation under advanced intersection types. As you can see, the variable result is essentially coerced using the <any> type assertion:

let result = <T & U>{};
for (let id in first) {
    (<any>result)[id] = (<any>first)[id];
}
Josh Crozier
  • 233,099
  • 56
  • 391
  • 304