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

React with Typescript passing objects via props

I’m trying to pass an object via props and having an issue understanding what Typescript wants.

Do I create an interface for Props than a separate interface for the properties within the object?

What I have:

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

import React from 'react';

interface Props { 
  link: object;
}

interface link {
  description: string;
  url: string;
}

const Link = (props: Props) => {
  const { link } = props;
  return (
    <div>
      <div>
        { link.description }({ link.url })
      </div>
    </div>
  );
};

export default Link;

Errors I’m getting:

Property 'description' does not exist on type 'object'.  TS2339
Property 'url' does not exist on type 'object'.  TS2339

>Solution :

use it like this, because Typescript can’t detect that if the object has property or not:

interface Props {
  link: {
    description: string;
    url: string;
  };
}

const Link = (props: Props) => {
  const { link } = props;
  return (
    <div>
      <div>
        {link.description}({link.url})
      </div>
    </div>
  );
};

export default Link;
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