简体   繁体   中英

React.createRef current type in typescript

I'm trying to find what to type React.createRef as. Header is a custom component. header.current always says

(property) React.RefObject.current: unknown Object is of type 'unknown'.

I can set it to type <any> but that's the easy way out. How do I get Typescript to play nice and stop complaining.

Example: React.createRef<any()

Fully code:

   const header= React.createRef();
    const { container } = render(
      <Header{...props} headerRef={header} />,
    );
    const el= hearder.current.getButtonElement("button");

I've even tried setting it to a HTMLDivElement which is what it returns.

const header= React.createRef<HTMLDivElement>();

but the below still gives me an error: (property) React.RefObject.current: HTMLDivElement | null Object is possibly 'null'.

const el= hearder.current.getButtonElement("button");

This makes sense. TypeScript is trying to warn you that calling getButtonElement on something that MIGHT be undefined is "dangerous". You can work around this by refining the type first, like this:

const header = React.createRef<HTMLDivElement>();

// In test
const currentHeader = header.current;
if (!currentHeader) {
    // Handle the case where header isn't set yet
}

currentHeader.getButtonElement("button"); // At this point TypeScript knows currentHeader can't be null so the type check passes

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM