CatBusStop
CatBusStop

Reputation: 3428

Using clipboardData in TypeScript

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?

Upvotes: 14

Views: 23540

Answers (4)

Ekaterina Tokareva
Ekaterina Tokareva

Reputation: 871

Use ClipboardEvent type (e.g.)

private onPaste(event: ClipboardEvent) {
    const {clipboardData} = event;
    const pastedText = clipboardData.getData('text');
}

Upvotes: 15

young-ceo
young-ceo

Reputation: 5384

Cast Event to ClipboardEvent like this:

element.bind('paste', (event: Event) => {
    let clipboardEvent: ClipboardEvent = <ClipboardEvent> event;
});

Upvotes: 2

bartburkhardt
bartburkhardt

Reputation: 7768

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

 var pastedData = e.originalEvent["clipboardData"].getData('text');

Upvotes: 10

CatBusStop
CatBusStop

Reputation: 3428

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.

Upvotes: 7

Related Questions