Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Converting from one type to another that is nearly the same

I’m passing a prop called defaultValue to a react component. The defaultValue has this typescript interface:

   interface IKeyValuePairProps {
      id: string;
      name: string;
    }

I pass it like this:

defaultValue={defaultValues && genes?.find((gene) => gene.id === defaultValues[0])}

Now genes is a interface that looks like this:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

interface IGeneticMatchingGene {
  id: string;
  name?: string;
}

Now they are more og less the same. What is the best way to pass the default find result as IKeyValuePairProps?

>Solution :

You can use as to assert that the type is something else.

defaultValue={defaultValues && genes?.find((gene) => gene.id === defaultValues[0]) as IKeyValuePairProps}

Note that you should only use type assertions if you’re sure that the type is correct.
https://www.typescriptlang.org/docs/handbook/2/everyday-types.html#type-assertions

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading