3

I am pretty new to React but with some Angular attempts before.

I was actually trying to implement a component which accepts a data model or object as parameter

Looks like this

import react from 'react'

interface SmbListItem{
    index:number;
    primary:string;
    secondary:string;
}
   

export default function SmbList({props}:SmbListItem){
    return(
        <>

        </>
    );
}

But its saying props does not exists on SmbListItem

What I did wrong?

Also requesting a suggestion on interface or types are the best option in this situation

Sandeep Thomas
  • 4,303
  • 14
  • 61
  • 132
  • you define `interface props` called `SmbListItem`. this is how your `SmbList props` looks like, when `destructuring` you should only mention the `key` among `interface props` – Azhar Uddin Sheikh Dec 22 '22 at 12:08

2 Answers2

2
import react from 'react'

interface SmbListItem{
    index:number;
    primary:string;
    secondary:string;
}
   

export default function SmbList({index, primary, secondary}:SmbListItem){
    return(
        <>

        </>
    );
}

There is no such props defined in your Interface Props

Even if you are not using Tsand you are sure about the props you would destructure your props like this

export default function SmbList({index, primary, secondary}){
    return(
        <></>
    );
}

For Your Second Question Have a look into Types vs Interface

  • Thanks a lot for that. But my confusion is if I have 10 properties in that interface, do I need to specify all those? Instead of accept it as a single object?? – Sandeep Thomas Dec 22 '22 at 13:23
  • 1
    @SandeepThomas it's depend what kind of interface you are buidling, you can extract reusable `property`, you can merge two `interface` etc etc, `Advanced Types, Generic TS` resolve to many code duplication , and provide dynamic typescripting – Azhar Uddin Sheikh Dec 22 '22 at 13:45
1
Hi @Sandeep Thomas,

First, You are trying to destructure the props parameter in the function definition, but you are not passing any props to the function. In that case, You need to use generic type function for that case.

If you're new to react-typescirpt world. Then, You need to read this first:- TypeScript Docs.

In short note:-

A generic type is a type that allows you to define a type or function with one or more placeholder types that can be filled in with specific types when the generic is used.

I found an good example for that:-

function identity<T>(arg: T): T {
  return arg;
}

let numberIdentity = identity(5);  // numberIdentity is of type number
let stringIdentity = identity("hello");  // stringIdentity is of type string

Here is example with your code:-

export default function SmbList<T extends SmbListItem>({ props }: T) {
    return <>// You code...</>;
}

The props parameter is of a type that extends the SmbListItem interface.

DSDmark
  • 1,045
  • 5
  • 11
  • 25