13

I'm trying to access data from the clipboard in TS1.6 using the following:

$(container).bind("paste", (e) => {
    var data = e.originalEvent.clipboardData.getData('text');
});

But it just gives me the following build error:

Property 'clipboardData' does not exist on type 'JQueryEventObject'

If I remove the 2nd line and debug it in Chrome 46, I can get at the clipboard data just by calling

e.originalEvent.clipboardData.getData('text');

I can't see clipboardData in the JQueryEventObject interface in the latest version of jQuery.d.ts but the question is - should it be there or is there a different way of retrieving data from the clipboard that TS currently supports?

CatBusStop
  • 3,347
  • 7
  • 42
  • 54
  • Possible duplicate of [JavaScript get clipboard data on paste event (Cross browser)](http://stackoverflow.com/questions/2176861/javascript-get-clipboard-data-on-paste-event-cross-browser) – Marcos Pérez Gude Dec 03 '15 at 09:15
  • Since Typescript 1.5 Property clipboardData has been removed from type Window. https://github.com/Microsoft/TypeScript/wiki/Breaking-Changes. – danywalls Dec 03 '15 at 09:18
  • 1
    It also looks like ClipboardEvent is being introduced in 1.8 so may just have to wait for that. https://github.com/Microsoft/TypeScript/issues/5363 – CatBusStop Dec 03 '15 at 09:42
  • Check answer https://stackoverflow.com/a/49922802/486867 – Manish Jain Dec 19 '18 at 22:54

4 Answers4

13

Use ClipboardEvent type (e.g.)

private onPaste(event: ClipboardEvent) {
    const {clipboardData} = event;
    const pastedText = clipboardData.getData('text');
}
Ekaterina Tokareva
  • 813
  • 11
  • 11
9

You can bypass the expected typescript type using the ["property"] approach

 var pastedData = e.originalEvent["clipboardData"].getData('text');
bartburkhardt
  • 7,498
  • 1
  • 18
  • 14
7

It seems until TS1.8, one (hacky) option I have found is to just extend Event with this:

interface Event {
    clipboardData: any;
}

I'm sure I could improve this by replacing any with something better, but it works for now.

CatBusStop
  • 3,347
  • 7
  • 42
  • 54
  • 3
    For other folks also stuck on pre-1.8 in some project: it's `clipboardData?: DataTransfer`. – Josh May 20 '16 at 15:56
2

Cast Event to ClipboardEvent like this:

element.bind('paste', (event: Event) => {
    let clipboardEvent: ClipboardEvent = <ClipboardEvent> event;
});
KimchiMan
  • 4,836
  • 6
  • 35
  • 41
  • 1
    I think it is need convert the original event: event.originalEvent I you find it right - please edit your answer. – user5260143 Aug 23 '18 at 08:56