【问题标题】:Use one or another interface type in Typescript/React在 Typescript/React 中使用一种或另一种接口类型
【发布时间】:2022-01-19 17:59:08
【问题描述】:

有这种类型:

export interface IMyTypes {
  First: {
    name: string;
    city: string;
    country: string;
    status: string;
  };
  Second: {
    name: string;
    age: number;
    height: number;
  };
}

这必须在组件中使用,但我不能让它同时接受,props 应该是 First 或 Second。

我可以让它为 First 工作:

import { IMyTypes } from '../my-types';

interface MyComponentProps {
  componentProps: ComponentProps<IMyTypes['First']>;
}

或者第二个:

interface MyComponentProps {
  componentProps: ComponentProps<IMyTypes['Second']>;
}

但无法使其接受其中一个,尝试如下但不正确:

interface MyComponentProps {
  componentProps: ComponentProps<IMyTypes['First' | 'Second']>;
}

有解决办法吗?

【问题讨论】:

  • ComponentProps&lt;IMyTypes['First'] | IMyTypes['Second']&gt;。在interface 中包装First 和Second 看起来很奇怪......
  • 或ComponentProps&lt;IMyTypes[keyof IMyTypes]&gt;
  • 大部分你会在以后重用'First'和'Second',所以只需将它们提取为单独的类型或接口并在componentProps中使用。如果有进一步的错误 - 请将其添加到帖子中
  • @AlekseyL。我收到以下错误:键入 'ComponentProps' 不能分配给类型 'ComponentProps'

标签: javascript typescript typescript-typings react-typescript


【解决方案1】:

解决问题的解决方案:

interface MyComponentProps {
  componentProps:
    | ComponentProps<IMyTypes['First']>
    | ComponentProps<IMyTypes['Second']>;
}

【讨论】:

    猜你喜欢
    • 2017-05-28
    • 2010-09-23
    • 2022-01-26
    • 1970-01-01
    • 1970-01-01
    • 2020-08-21
    • 1970-01-01
    • 2019-02-08
    • 1970-01-01
    相关资源
    最近更新 更多