【译文】TypeScript笔记3/17:访问非导出组件属性类型

1,280 阅读1分钟

原文地址: Notes on TypeScript: Accessing Non Exported Component Prop Types

本系列文章共17篇,此为第3篇

关于TypeScript的其他笔记

【译文】TypeScript笔记1/17:Pick,Exclude与高阶组件

【译文】TypeScript笔记2/17:render props

低级方法

(译者注:总感觉作者这一小节的内容写的怪怪的,例子貌似也有问题,推荐直接使用下一小节的高级方法)

访问非导出类型的一种方法是自己写一个类型抽取辅助工具:

type componentProps<T> = T extends
  | React.ComponentType<infer Props>
  | React.Component<infer Props>
  ? Props
  : never;

让我们深入研究一下这个辅助工具,来好好理解TypeScript是如何推断React的组件属性的。 React.ComponentType是类组件、函数组件的别名,使用infer P可以让TypeScript推断ComponentTypeReact.Component本身的属性Props

接着要么返回被推断出的Props,要么返回nevernever类型用来代表从来不会发生的值。例如,函数抛出异常。

componentProps辅助工具可以用来访问组件属性了。

type User = {
  id: number;
  name: string;
  title: string;
  location: string;
};

const User = (props: User) => { // 译者注:type User与const User重名???
  return (
    <div>
      {/* ... */}
    </div>
  )
};

type ActionPropTypes = React.ComponentProps<typeof User>; // 译者注:这里应该是调用componentProps这个吧???

const UserWrapper = (props: ActionPropTypes) => {
  return (
    <div>
      <div>{props.name}</div>
      <User {...props} />
    </div>
  );
};

现代方法

有意思的是,现在我们也可以使用React类型提供的React.ComponentProps了。重写上面的例子:

type ActionPropTypes = React.ComponentProps<typeof User>;

更多信息

React-TypeScript-Cheatsheet: Basic

React-TypeScript-Cheatsheet: Advanced

Answer on Stackoverflow