TypeScript icon indicating copy to clipboard operation
TypeScript copied to clipboard

typing for navigator.clipboard

Open Manish3177 opened this issue 1 year ago • 4 comments

⚙ Compilation target

ES5

⚙ Library

None

Missing / Incorrect Definition

lib.dom.ts defines interface Navigator with:

`/**

  • Available only in secure contexts.
  • MDN Reference */ readonly clipboard: Clipboard;`

This allows writing code like navigator.clipboard.readText() which crashes in unsecure environments (over HTTP).

Fix suggestion: Change the return type in typing to Clipboard | null to force a null check in consuming code. This is kind of a breaking change but that's the point.

Sample Code

navigator.clipboard.readText() ;will crash over HTTP

Documentation Link

No response

Manish3177 avatar Jun 27 '24 21:06 Manish3177

This is intentional. There are a lot of calls like this that only work in a secure context. If you know your code is always going to run over HTTPS, it would be incredibly annoying and counterproductive if the compiler forced you do either do a null check or add a non-null assertion to every such call.

fatcerberus avatar Jun 27 '24 22:06 fatcerberus

See also https://github.com/microsoft/TypeScript/issues/52044 which was marked WAI.

fatcerberus avatar Jun 27 '24 22:06 fatcerberus

Thanks for those links @fatcerberus but in my humble opinion, the "it works in secure context" argument is not much better than a "but it works on my machine" argument. Those that don't care about running in contexts where the property can be null are free to use optional chaining or non-null assertion (if they want to assert they really don't care). A single character isn't counter-productive or something that causes clutter. A false assurance on the other hand is bad for people who care.

Manish3177 avatar Jun 27 '24 23:06 Manish3177

“but it works on my machine”

This is a bad analogy because HTTP/HTTPS is a server-side concern and not something that would be affected by end-user configuration.

Anyway I’m just telling you the position of the TS maintainers on this - it’s not considered a bug for the reasons stated before and that’s not likely to change.

fatcerberus avatar Jun 27 '24 23:06 fatcerberus

This issue has been marked as "Working as Intended" and has seen no recent activity. It has been automatically closed for house-keeping purposes.

typescript-bot avatar Jul 04 '24 01:07 typescript-bot