简体   繁体   中英

React Hooks TypeScript inheriting parent state & function types in child

I'm looking for ways to inherit parent state & function types in child component so that I do not have to redefine them in child component.

I have parent component as follows:

const TagPopupModal: React.FC = () => {
// state
  const [addTagPressed, setAddTagPressed] = useState<boolean>(false);
  const [tagList, setTagList] = useState<userTagType['tags'][]>(
    [],
  );

// function
  function addToTagList(tag: tagListType) {
   ...
  }

return (
  ...
  <TagListView 
    addTagPressed={addTagPressed}
    tagList={tagList}
    addToTagList={addToTagList}
  />
)
}

In parent component, I have defined the types for the state and parameter type for the function. Those are passed to child component.

Now in child component I have following:

interface PropTypes {
  addTagPressed:boolean;
  tagList: Array<userTagType['tags']>;
  addToTagList: (value: taglistType) => void;
}

const TagListView: React.FC<PropTypes> = ({
  addTagPressed, 
  tagList,
  addToTagList,
}) =>{
   ...
}

As you can see I had to define the same types for the props again, but using interface, in the child component. This is time-consuming, is there ways to directly inherit the types of the state and functions from the parent?

What would be the most efficient way?

Thanks,

You could export your interface for PropTypes and consume that elsewhere, eg as const [tagList, setTagList] = useState<PropTypes['tagList']>([]);

You won't necessarily save much raw keyboard mashing, but it will help keep your types consistent and reusable.

import { TagListView, PropTypes } from '../TagListView';

const TagPopupModal: React.FC = () => {
// state
  const [addTagPressed, setAddTagPressed] = useState(false);
  const [tagList, setTagList] = useState<PropTypes['tagList']>(
    [],
  );

// function
  const addToTagList: PropTypes['addToTagList'] = (tag) => {
   ...
  }

return (
  ...
  <TagListView 
    addTagPressed={addTagPressed}
    tagList={tagList}
    addToTagList={addToTagList}
  />
)
}

Note that you don't need to be super vigilant about declaring explicit types in general. useState(false) for example will automatically infer the type of that state as boolean . And if you declare the function addToTagList as a const and set its type to be what is defined in PropTypes , TS will automatically know that the parameter tag is supposed to have a given type.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM