输入react-props作为`type`或`interface` [英] typed react - props as `type` or an `interface`

查看:80
本文介绍了输入react-props作为`type`或`interface`的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有反应码

导出默认类MyComponent扩展了Component< Props,State>

问题是,我是否会编写 type interface 之类的道具?

The question is, do I write props like a type or an interface?

type Props = {
    isActive: Boolean,
    onClick: Function
}

interface Props {
    isActive: Boolean,
    onClick: Function
}

还有,当我不使用打字稿,而是经典的webpack + babel设置时,方向是什么?

also, what is the direrence, when I am not using typescript, but classic webpack+babel setup?

或者,对我来说,它甚至有多重要吗?

Or, does it even matter much to mee?

推荐答案

现在是2020年,在几乎所有带有 React 道具(通用类型)的情况下,我都倾向于 type vs接口文章位于此处).只能用类型别名表示的常见情况:

It is 2020 now and I would favor type in almost all cases with React props (general type vs interface post is here). Common cases that can be only expressed with type aliases:

// given some props from another comp that are to be altered
type ExternalProps = { a: string; b: { c: number } };

type Props_IndexType = ExternalProps["b"]; // { c: number; }
type Props_MappedType = { [K in keyof ExternalProps]: number }; // { a: number; b: number; }
type Props_DiscriminatedUnionType = { tag: "tag1"; foo: string } | { tag: "tag2"; foo: boolean}
type Props_typeOf = { foo: string } & typeof defaultProps; // see class comp example

// conditional types - ok, this one is a bit contrived, but you get the point
type Props_ConditionalType<T> = T extends true ? { a: string } : { b: number };
const Comp = <T extends {}>(props: Props_ConditionalType<T>) =>
  <div>{"a" in props && (props as any).a}</div>
render(<Comp<true> a="foo" />, document.getElementById("root"));

类组分为了说明示例(OP提到他们,但上述情况也适用于挂钩):

Class component example for illustration (OP mentions them, but above cases also apply for Hooks):

// cannot do that with interfaces
type Props = ({ tag: "tag1"; foo: string } | { tag: "tag2"; foo: boolean }) &
  typeof defaultProps;
type State = typeof initState;

const defaultProps = { a: "A" };
const initState = { c: "C" };

class App extends React.Component<Props, State> {
  static readonly defaultProps = defaultProps;
  state = initState;

  render() { ... }
}

render(<App tag="tag1" foo="foo" />, document.getElementById("root"));

仅有的情况下,我将考虑接口:

The only cases, I would consider interfaces:

  • 您在以下类型中对道具类型进行声明合并全球范围(如今不常见)
  • 您要隐藏类型实现的详细信息,因为接口会在错误消息,IDE类型信息等中创建新名称.(
  • You do declaration merging of prop types in the global scope (uncommon nowadays)
  • You want to hide type implementation details, as interfaces create a new name used in error messaged, IDE type infos etc. (docs)

这篇关于输入react-props作为`type`或`interface`的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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