microsoft / TypeScript

TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
https://www.typescriptlang.org
Apache License 2.0
100.77k stars 12.46k forks source link

Image element src property does not allow URL assignment #43066

Open TimvdLippe opened 3 years ago

TimvdLippe commented 3 years ago

Bug Report

🔎 Search Terms

image src dom

🕗 Version & Regression Information

⏯ Playground Link

Playground link with relevant code

💻 Code

let image = document.createElement('img');
image.src = new URL("http://google.com");
console.log(image.src)

🙁 Actual behavior

Type 'URL' is not assignable to type 'string'.(2322)

🙂 Expected behavior

Compiles cleanly (confirmed supported per https://github.com/whatwg/html/issues/6440)

TimvdLippe commented 3 years ago

Previous occurrences of this kind of issue:

At this point, should we assume that USVString implies string | URL? The handling of USVString is currently implemented in https://github.com/microsoft/TypeScript-DOM-lib-generator/blob/07ea4e8bf58f9907d22024cca6433e002fffd251/src/helpers.ts#L6 I am not sure how many other IDL definitions use USVString, but wouldn't accept a URL (which would be implicitly .toString'd per the linked HTML issue)

CC @domenic do you mind confirming if we can assume type USVString = string | URL in TypeScript or am I still misunderstanding the terminology here 😄

domenic commented 3 years ago

It's more subtle than that. Every DOMString or USVString will convert any input to a string. Technically, everything in JavaScript is convertible to a string, at the very least through Object.prototype.toString(). So hard-coding URL doesn't make sense to me.

TimvdLippe commented 3 years ago

Ah right. Yes I understand that now. Thanks again for the explanation!

DanielRosenwasser commented 3 years ago

You want separate types for reading and writing properties, which @RyanCavanaugh is iterating on over at #42425.

I guess we did discuss a few things in a previous design meeting about how much of lib.d.ts needed to change and punted on it, but this seems like a reasonable one (write of URL | string, read of string).

DanielRosenwasser commented 3 years ago

So hard-coding URL doesn't make sense to me.

We'd want to be more permissive to a degree; letting anything in with a toString() seems undesirable, whereas unblocking a scenario like assigning URL instances to ~a property called url~ the src property seems reasonable.

RyanCavanaugh commented 3 years ago

Tracking at #2521. We can update the lib once that's checked in