1

I've some old code like this

import * as $ from "jquery";
type Foo = string | object | JQuery;

let x: Foo = { bar: 33}; // just a generic object
let y: Foo = { stop: 33}; // meant to a generic object, but...

With Typescript 3.5.1 I get this error for y.

Types of property stop are incompatible. Type number is not assignable to type { (queue: string, clearQueue?: boolean, jumpToEnd?: boolean): JQuery<HTMLElement>; (clearQueue?: boolean, jumpToEnd?: boolean): JQuery<HTMLElement>; }.

Obviously it's inferring (incorrectly) that {stop:33} is meant to be a JQuery?

Is this a compiler bug? If not, how to avoid the problem?


To explain why Foo is defined that way... It's used as a parameter type to functions, allowing the conversion of Foo to an XML string, like this. Depending on the type of Foo it's treated as an existing XML string, a DOM node, or a generic object which is translated to xml.

private paramToString(data: Foo): string {
  let result = isJquery(data) ? new XMLSerializer().serializeToString(data[0]) :
    (typeof data === "string" ? data : new XML2JS.Builder().buildObject(data));
  return result;
  }
6
  • 1
    If it's meant to be a generic object, why declare it with type Foo? I'm having trouble seeing what Foo is for. I get string | JQuery, but object? Commented Jun 7, 2019 at 7:00
  • 1
    Change the key name instead of stop and try. Because may be some stop() functions are there with the same name in inside of JQuery object. Commented Jun 7, 2019 at 7:02
  • @T.J.Crowder see my edit. Ramesh: Yes, that's what's happening, but changing the key name isn't an option for me here. Commented Jun 7, 2019 at 7:19
  • Try doing type Foo = string | object; Commented Jun 7, 2019 at 7:22
  • Probably casting it explicitly would get rid of the error? Commented Jun 7, 2019 at 7:32

1 Answer 1

2

Yup, looks like JQuery type has stop defined and it's not a number. The simplest solution is to explicitly tell that your value is a simple object.

let y: Foo = {stop: 33} as object;
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.