Getting the error
error TS2304: Cannot find name 'ClipboardItem'
when trying to create a ClipboardItem
for navigator.clipboard.write()
.
const clipboardItemInput = new ClipboardItem({'image/png' : blobInput});
await navigator.clipboard.write([clipboardItemInput]);
I am using Angular 6. Do I need to add any dependencies, or is there any other method?
For TypeScript 4.4 and higher
TypeScript 4.4 updated the standard definitions library with missing interfaces and methods (full list of changes), so everything should work out-of-the-box. The following sample code now compiles without additional interfaces/declaration merges:
Playground
For TypeScript 4.3 and lower
As of 2021, the TypeScript standard library is still missing a definition for the Clipboard API (and that is the reason for the "Cannot find name 'ClipboardItem'" error). There is an open issue on the source repository and a pull request on the DOM lib generator repository (because the standard library is autogenerated) that should address the issue.
In the meantime, you can add the following definitions matching how the standard library defines other global interfaces (do not forget to add a triple-slash directive
/// <reference types="../../index" />
at the top of the importing file):Note that the
ClipboardItemData
is defined to take eitherBlob
,string
, or a promise that returns one of the former and not just aBlob
(see the MDN reference, for example). It also does not hurt to augment theClipboard
interface with missingread
andwrite
methods:Finally, let's test that the definitions work as expected:
Playground