I have a large existing project that is being converted to typescript and will eventually be refactored and then put into Angular. The current project has a lot of Jquery in it. I have a current @types implemented into the project.
The issue is that this line
if (["Priority", "PM"].indexOf($('option:selected', this).val()) >= 0) {
is creating an error because of type definitions. I get [TS] Argument of type 'string | number | string[]' is not assignable to parameter of type 'string'. Because the indexOf is defined as "(method) Array.indexOf(searchElement: string, fromIndex?: number): number" and Jquery's .val is defined as "JQuery.val(): string | number | string[] (+1 overload)".
I need a way to override the .val definition, to just string so that I can get it to compile, for lines like this without overriding .val for the whole project. I have many lines that are like this in the project so I'm not able to just rewrite everyone of them yet. Eventually we will get rid of Jquery entirely. If anyone can point me to the right direction that would be great.
The error "Argument of type is not assignable to parameter of type 'never'" occurs when we declare an empty array without explicitly typing it and attempt to add elements to it. To solve the error, explicitly type the empty array, e.g. const arr: string[] = []; .
The "Type 'string' is not assignable to type" TypeScript error occurs when we try to assign a value of type string to something that expects a different type, e.g. a more specific string literal type or an enum. To solve the error use a const or a type assertion.
The error "Argument of type string | undefined is not assignable to parameter of type string" occurs when a possibly undefined value is passed to a function that expects a string . To solve the error, use a type guard to verify the value is a string before passing it to the function.
The "Type 'string | undefined' is not assignable to type string" error occurs when a possibly undefined value is assigned to something that expects a string . To solve the error, use the non-null assertion operator or a type guard to verify the value is a string before the assignment.
I finally figured out how to make it work. I was able to cast the type string to it. Since I had that exact line several places in the project I created a variable like this:
let optSel: string = <string>$('option:selected', this).val();
if ($(["Priority", "PM"]).index(optSel) >= 0) {
This allowed me to make sure that the .val type was a string which matched the indexOf requirement of Array.indexOf(searchElement: string. Hope this helps someone.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With