Martin
Martin

Reputation: 1419

How to "use" a function type defined in an interface

Given an interface:

interface MyProps {
  onEvent: (name: string, data: any) => void;
}

How can I use that function type to prevent unused parameter errors when compiling?

eventHandler = (name: string, data: any) => {
  console.log(data);
}

Because currently I get a compilation error of unused parameter for the "name", but I cannot remove it because it would break the signature of the underlying type.

I was hoping to do something like this, although obviously this doesn't work!

eventHandler: MyProps.onEvent = (name, data) => {
  console.log(data);
}

Upvotes: 1

Views: 67

Answers (1)

Titian Cernicova-Dragomir
Titian Cernicova-Dragomir

Reputation: 249466

You just have the syntax a bit wrong you need to use ['name']. This is called an indexed type query

interface MyProps {
    onEvent: (name: string, data: any) => void;
}

let eventHandler: MyProps['onEvent'] = (name, data) => {
    console.log(data);
}

Upvotes: 1

Related Questions