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:
declare const image: ClipboardItemData;
(async () => {
const item = new ClipboardItem({ "image/png": image });
const files = await navigator.clipboard.read();
if( files.length ) return;
await navigator.clipboard.write([item]);
})();
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):
interface ClipboardItem {
readonly types: string[];
readonly presentationStyle: "unspecified" | "inline" | "attachment";
getType(): Promise<Blob>;
}
interface ClipboardItemData {
[mimeType: string]: Blob | string | Promise<Blob | string>;
}
declare var ClipboardItem: {
prototype: ClipboardItem;
new (itemData: ClipboardItemData): ClipboardItem;
};
Note that the ClipboardItemData
is defined to take either Blob
, string
, or a promise that returns one of the former and not just a Blob
(see the MDN reference, for example). It also does not hurt to augment the Clipboard
interface with missing read
and write
methods:
interface Clipboard {
read(): Promise<DataTransfer>;
write(data: ClipboardItem[]): Promise<void>;
}
Finally, let's test that the definitions work as expected:
declare const image: Blob;
(async () => {
const item = new ClipboardItem({ ["image/png"]: image });
const { files } = await navigator.clipboard.read();
if( files.length ) return;
await navigator.clipboard.write([item]);
})();
Playground