Home > Back-end >  React Typescript: how to forcefully pass a prop regardless of the typing
React Typescript: how to forcefully pass a prop regardless of the typing

Time:07-20

I'm converting a project to Typescript, and one of the libraries I'm using seems to have incorrect typings. I was passing a prop (component) before Typescript, and it was working for what I needed. Now adding the prop gives a type error, since it's not a member of the Library Component's Prop interface.

e.g.,

<LibraryComponent className="foo"/> // fails since className isn't a specified prop

Since I know the prop was working, it seems like the library incorrectly omitted it (or didn't want it to be part of the interface).

I know I could use declaration merging in a custom types file to add the prop, but I'm also curious now: is there any way to forcefully override the type checks and pass in the prop anyways? Something similiar to "foo as any" to override type checking when passing something to a function.

CodePudding user response:

One option is to put the prop into an object, then spread the object into the props list.

<LibraryComponent {...{ className: "foo" }} />

This will still raise an error if a prop that is required isn't present, or is the wrong type - it'll just let you pass others as well, even if they aren't used (or aren't typed properly) in the child.

  • Related