0

The example below outputs an instance of SomeClass - this works as expected. Question: Is there a way to omit the DisplayModelComponentProps interface and directly pass the object to be displayed as prop?

class SomeClass {
  public someProperty:string = "some string";
  public someFunction():string { return "another string"; }
}

interface DisplayModelComponentProps {
    obj:SomeClass
}

const DisplayModelComponent: React.FC<DisplayModelComponentProps> = props => {
  return(<p>{props.obj.someProperty}</p>
  )
}

export function Test(): JSX.Element {
 const someObj:SomeClass = new SomeClass();
 const props = { obj: someObj }

  return(<div><DisplayModelComponent {...props}></DisplayModelComponent></div>)
}

When I change the code so the DisplayModelComponent takes a SomeClass as prop I get this error (because the function is lost on destructuring):

Property 'someFunction' is missing in type '{ someProperty: string; }' but required in type 'SomeClass'.

1 Answer 1

1

The error happens because when spreading the instance of SomeClass the someFunction property is lost. That's why Typescript is complaining that someFunction is missing in the component props.

You can check this answer regarding the spread operator and how properties are copied: Does the spread operator not copy over the prototype?

With that in mind, I don't think you are going to be able to do it as long as methods are involved in the class you are trying to use as interface.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for your answer. I figured out this would do the job but its definetely not a clean solution: return(<div><DisplayModelComponent {...{...someObj, someFunction:()=>""}}></DisplayModelComponent></div>)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.