简体   繁体   English

为什么 typescript 不能确保在 React 中添加额外属性的通用高阶组件中的类型安全?

[英]Why typescript does not ensure type safety in a generic higher order component that adds additional properties in React?

I'm trying to create a generic higher order component and type safety is not checked.我正在尝试创建一个通用的高阶组件,但未检查类型安全性。 When doing the same but in a not generic way, the type safety is checked as expected.当以非通用方式执行相同但不通用的操作时,会按预期检查类型安全性。

interface IBaseProps {
  baseValue?: string;
}

const Base = (props: IBaseProps) => {
  return <span>{"value: " + props.baseValue}</span>;
};

interface IExtraProps {
  extraValue?: string;
}

const foo = <T extends IBaseProps>(
  Element: React.ComponentType<T>
): React.ComponentType<T & IExtraProps> => (props: T & IExtraProps) => {
  const baseValue = `${props.baseValue} extra value: ${props.extraValue}`;
  return <Element {...props} baseValue={baseValue} />; // example
};

const bar = <T extends IBaseProps>(
  Element: React.ComponentType<T>
): React.ComponentType<T & IExtraProps> => (props: T & IExtraProps) => {
  return <Element {...props} baseValue={42} />; // NO error, why?
};

const baz = <T extends IBaseProps>(
  Element: React.ComponentType<T>
): React.ComponentType<T & IExtraProps> => (props: T & IExtraProps) => {
  return <Element {...props} unknownProp={42} />; // NO error, why?
};

const bag = (props:IBaseProps) => {
  const baseValue = props.baseValue + ' augmented'
  return <Base {...props} baseValue={42} />; // ok, error is detected
}

Demo can be foundhere演示可以在这里找到

How to make Typescript check types correctly?如何使 Typescript 正确检查类型?

Everything is right with typescript. The Base component is declared above and has a type to IBaseProps.That is why it shows an error. typescript 一切正常。Base 组件在上面声明并且具有 IBaseProps 的类型。这就是它显示错误的原因。

The bar has酒吧有

React.ComponentType<T & IExtraProps> 

It basically means that T can be any type.它基本上意味着 T 可以是任何类型。 So it is not showing any errors.所以它没有显示任何错误。

The others also have T & IExtraProps types.其他人也有 T & IExtraProps 类型。 Check it by hovering to any of them ( bar, baz, foo, bag ).通过将鼠标悬停在其中任何一个(bar、baz、foo、bag)上来检查它。 Everything is working correctly in this code.这段代码中的一切都正常工作。

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

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