2

I use React with typescript and react-bootstrap to create dropdown list:

ipc__handleSelect = (eventKey: any, event: any) => {
}

render() {

    return (
        <Dropdown>
            <Dropdown.Toggle>Text</Dropdown.Toggle>
            <Dropdown.Menu>
                <Dropdown.Item
                    key         = 'key1'
                    eventKey    = 'key1'
                    onSelect    = {this.ipc__handleSelect}
                >Item</Dropdown.Item>
            </Dropdown.Menu>
        </Dropdown>
    );
}

help identify data types

  1. event: any - what type should I write?

  2. eventKey: any - what type should I write?

when I write eventKey: string (because the key is a string), I get error:

Type '(eventKey: string, event: any) => void' is not assignable to type 'SelectCallback'. Types of parameters 'eventKey' and 'eventKey' are incompatible. Type 'string | null' is not assignable to type 'string'. Type 'null' is not assignable to type 'string'.

why does null even occur there?

1 Answer 1

4

If you look at the react-bootstrap library code, you will see that Dropdown. Item has an onSelect of type SelectCallback and SelectCallback is like this:

export type SelectCallback = (
  eventKey: string | null,
  e: React.SyntheticEvent<unknown>,
) => void;

Since you assign that your handler took in only string type and Dropdown Item onSelect gives string|null to eventKey, you got an error that it cannot be mapped.

Sign up to request clarification or add additional context in comments.

2 Comments

If I write eventKey: string | null then an error is displayed Type 'string | null' is not assignable to type 'string | undefined', if wite event: React.SyntheticEvent<unknown> - error: Property 'className' does not exist on type 'EventTarget'. when use event.target.className in handleSelect
I don't get the first error where it said Type 'string | null' is not assignable to type 'string | undefined' when I tried it, what version of react-bootstrap and typescript are you using? For the second one, since the type of event.target is EventTarget, for you to get HTML attributes, you have to cast it to HTMLElement like this (event.target as HTMLElement).className

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.