输入react-props作为`type`或`interface`

Iva*_*nák 6 typescript reactjs flowtype

我有反应码

export default class MyComponent extends Component<Props,State>

问题是,我会写像a type或an 这样的道具interface吗?

type Props = {
    isActive: Boolean,
    onClick: Function
}
Run Code Online (Sandbox Code Playgroud)

要么

interface Props {
    isActive: Boolean,
    onClick: Function
}
Run Code Online (Sandbox Code Playgroud)

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

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

for*_*d04 22

现在是 2020 年,type在几乎所有使用React道具的情况下,我都会赞成(此处为通用类型与界面帖子)。只能用类型别名表示的常见情况:

// 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"));
Run Code Online (Sandbox Code Playgroud)

用于说明的类组件示例(OP 提到了它们,但上述情况也适用于 Hook):

// 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"));
Run Code Online (Sandbox Code Playgroud)

唯一的情况,我会考虑接口:

  • 您在全局范围内对 prop 类型进行声明合并(现在不常见)
  • 您想隐藏类型实现细节,因为接口创建了一个用于错误消息、IDE 类型信息等的新名称(文档


CRi*_*ice 6

接口比相应的类型声明要强大一些,但是对于一组react道具,这可能并不重要。您可以在此问题中了解类型和接口之间的区别。

由于您不太可能扩展该接口或将其扩展到其他地方,因此使用其中任何一个都可能很好。但是我要说的是,通常首选接口来定义对象类型,因为它们更加灵活。

  • 这个答案可能已经过时了。至于“更强大”的部分,也可以很容易地提出相反的论点。查看:/sf/ask/2606361481/#comment96004001_52682220。互联网上也有更多关于界面是否真的“更好”的讨论。 (4认同)