简体   繁体   English

typescript React.FC如何表达给定道具(来自用户)与组件内的最终道具之间的差异

[英]typescript React.FC how to express difference between given props(from user) to final props inside the component

the props available inside component Comp can potentially be different from what the user passed to the component.组件Comp中可用的道具可能与用户传递给组件的道具不同。 I can think of 2 such scenarios:我可以想到2个这样的场景:

  • when using defaultProps: for example:使用 defaultProps 时:例如:

     import React, { FC } from "react"; interface CompProps { name?: string; } const Comp: FC<CompProps> = (props) => { return <div>{props.name.toUpperCase()}</div>; // ^ TS2532: Object is possibly 'undefined'. }; Comp.defaultProps = { name: "", };

    the prop name is optional so props.name could be undefined, but because name has default prop it will never be undefined(unless undefined be passed explicitly) ( possible solution )道具name是可选的,因此props.name可以是未定义的,但因为name具有默认道具,所以它永远不会未定义(除非明确传递undefined )(可能的解决方案

  • when props are injected from parents using React.cloneElement .当使用React.cloneElement从父母注入道具时。 props may be implicitly passed from parent to children without typescript knowing it. props 可能会在 typescript 不知道的情况下从父级隐式传递给子级。

currently, in order to fix this, I create another interface FinalCompProps which will contain the actual final props, and then casting it into props .目前,为了解决这个问题,我创建了另一个接口FinalCompProps ,它将包含实际的最终道具,然后将其转换为props

import React, { FC } from "react";

interface CompProps {
  name?: string;
}
interface FinalCompProps {
  name: string;
}

const Comp: FC<CompProps> = (_props) => {
  const props = _props as FinalCompProps // casting
  return <div>{props.name.toUpperCase()}</div>; // no errors
};
Comp.defaultProps = {
  name: "",
};

This works fine, but I wondered, there is no way to pass into React.FC expected type from the user and final props actually passed to the component?这工作正常,但我想知道,没有办法从用户传递到 React.FC 预期类型,最终道具实际上传递给组件?

Looking at the type definition React.FC查看类型定义 React.FC

type FC<P = {}> = FunctionComponent<P>;

interface FunctionComponent<P = {}> {
  (props: P, context?: any): ReactElement<any, any> | null;
  propTypes?: WeakValidationMap<P> | undefined;
  contextTypes?: ValidationMap<any> | undefined;
  defaultProps?: Partial<P> | undefined;
  displayName?: string | undefined;
}

It looks like there is no option pass such 'FinalProps', and typescript will always end auto-suggest the props passed into React.FC when passing props to Comp看起来没有选项传递这样的“FinalProps”,并且打字稿总是会在将道具传递给Comp时自动提示传递给 React.FC 的道具

I think the easiest solution to this is:我认为最简单的解决方案是:

props.name?.toUpperCase()

Then if name is undefined, it won't call toUpperCase() .然后,如果name未定义,则不会调用toUpperCase()

The point of Typescript is to define the types so you don't want to change the prop types. Typescript 的重点是定义类型,因此您不想更改道具类型。

What do you want to happen if name is undefined?如果name未定义,你想发生什么?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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