paulywill
paulywill

Reputation: 683

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:

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

Upvotes: 1

Views: 514

Answers (2)

Daniel Baldi
Daniel Baldi

Reputation: 920

object is never a good way to type things in TS, as you can't retrieve any information from the object (its properties and much less its properties' types). Also, you're not using this link interface that you're creating! You need to use it to type your props:

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

interface Props { 
  link: Link;
}

Upvotes: 4

Jamal
Jamal

Reputation: 848

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;

Upvotes: 1

Related Questions