Home > Software engineering >  Converting from one type to another that is nearly the same
Converting from one type to another that is nearly the same

Time:10-05

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:

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?

CodePudding user response:

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

  • Related