Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to define that component passed must have certain props but allow extra props too

I am passing a component as a prop.

This is defined as below.

export type TableProps<T> = {
  contents: T[],
  loadContents: () => Promise<T[]>
};

This works fine, but I'd like to update this definition to say, at least above props should exist, but to allow additional props.

Is there a definition I can use to do this. For instance, I'd like a component with the following signature to be accepted.

type Props = {
  onChangeMark: (val: string) => void,
  ...TableProps<Attendance>
};

I've tried defining them as an interface but they are still being rejected.

interface TableProps<T> {
  contents: T[],
  loadContents: () => Promise<T[]>
};

Update

I think this demostrates the issues I am having Link

Update 2

@Rajesh 's solution doesnt seem to work , have tried here

like image 664
Tom Avatar asked Jan 30 '18 15:01

Tom


People also ask

How do you pass props to a component passed as prop?

You can pass a component as props in React by using the built-in children prop. All elements you pass between the opening and closing tags of a component get assigned to the children prop. Copied!

How do you pass two props in one component?

Method 1: We can make a separate method for the event and call all the props method in that method. Method 2: We can create an anonymous function and call all the props method inside the anonymous method.

Can we pass multiple props?

Aside from passing multiple props at once, in this example, you also see the age prop is a number data type. This demonstrates that you can pass any type of data available in JavaScript — such as number , Boolean , or object — into props.


2 Answers

You can try something like this:

interface IDummy {
  value: string;
  propName: string;
  [key: string]: any;
}

What this will do is, it will force you to pass value and propName properties in object but you can have any other properties.

Sample

like image 162
Rajesh Avatar answered Sep 27 '22 20:09

Rajesh


What I have done in cases like this is to define Props as a union of TableProps and per-component props:

type Props = TableProps<Attendance> & {
  onChangeMark: (val: string) => void
};

In that case I would keep TableProps as an object type, not an interface.

It is also possible to use interfaces if both TableProps and Props are defined as interfaces like this:

interface TableProps<T> {
  contents: T[],
  loadContents(): Promise<T[]>
}

interface Props extends TableProps<Attendance> {
  onChangeMark(val: string): void
}

I think that Flow might have an easier time with the interface solution. But I don't have any particular evidence to back up that hunch.

like image 20
Jesse Hallett Avatar answered Sep 27 '22 20:09

Jesse Hallett