Typescript React:访问组件属性类型 [英] Typescript React: Access component property types

查看:92
本文介绍了Typescript React:访问组件属性类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

npm package @types/react 允许我们在 TypeScript 应用程序中使用 React.我们将组件定义为

npm package @types/react allows us to use React inside of our TypeScript apps. We define components as

type Props = {...}

type State = {...}

export default class MyComponent extends React.Component<Props, State> {
}

这里我们必须声明组件 props 和 state 的类型(在类型变量中).

here we have to declare types for component props and state (in type variables).

在我们声明类型之后,TypeScript 使用它来验证我们组件的使用情况(传递给它的 props 的形状).

After we declared that types, TypeScript uses that to validate the usage of our component (the shape of props passed to it).

我想围绕这样一个组件创建一个容器.容器将重用组件的道具.但是为了创建另一个具有相同 props 的组件,我必须再次重新声明 props 的类型.或者从原始组件文件中导出并导入到容器中:

I want to create a container around such a component. The container will reuse the props of the component. But in order to create another component with the same props I have to redeclare the types for props again. Or export them from the original component file and import into container:

// original file
export type Props = {...}

// container file
import MyComponent, { Props } from './original'

但我已经从该文件中导入了 MyComponent.这个组件已经包含了关于它消耗的 props 的信息(感谢 React.Component 中的类型变量).

But I'm already importing the MyComponent from that file. This component already contains information about the props it consumes (thanks to type variables in React.Component).

问题是如何在不显式导出/导入 props 类型的情况下从组件类本身访问该信息?

我想要类似的东西:

import MyComponent from './MyComponent'

type Props = MyComponent.Props // <= here access the component prop types

export default class MyContainer extends React.Component<Props, {}> {}

推荐答案

2019:注意到以上所有答案都已经过时,所以这里是一个新答案.

2019: noticed all answers above are quite outdated so here is a fresh one.

在较新的 TS 版本中,您可以使用查找类型.

With newer TS versions you can use lookup types.

type ViewProps = View['props']

尽管非常方便,但它只适用于类组件.

React typedef 附带一个实用程序,可以从任何组件中提取 props 的类型.

The React typedefs ship with an utility to extract the type of the props from any component.

type ViewProps = React.ComponentProps<typeof View>

type InputProps = React.ComponentProps<'input'>

这有点冗长,但与类型查找解决方案不同:

This is a bit more verbose, but unlike the type lookup solution:

  • 开发者意图更加明确
  • 这将适用于功能组件和类组件

所有这些都使该解决方案成为最具前瞻性的解决方案:如果您决定从类迁移到挂钩,则无需重构任何客户端代码.

All this makes this solution the most future-proof one: if you decide to migrate from classes to hooks, you won't need to refactor any client code.

这篇关于Typescript React:访问组件属性类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆