0

我的一个界面中有以下类型:

export interface CardProps {
  component?:
    |  'BatteryHealth'
    |  'DriveHealth'
    |  'SSDTrim'
    |  'ThermalDashboard'
    |  'MainFeature'
    |  'DiskSpace'
    |  'Benchmark'
    |  'Scanning'
    |  'Uninstaller'

  // other props of the interface
}

我正在使用该接口为与此相关的另一个对象创建类型:

const components: Record<CardProps['component'], React.ComponentType> {
  // and here it gives me keys for that new components object
  // that match the possible values of the component property, like so:
  BatteryHealth: BatteryHealthComponent,
  DriveHealth: DriveHealthComponent,
  // ...
  // which is exactly what I want.
}

现在事情发生了一些变化,我不得不重新设计那个界面,现在看起来像这样:

export interface CardProps {
  component?:
    | { type: 'BatteryHealth'; props: BatteryHealthCardProps }
    | { type: 'DriveHealth'; props: DriveHealthCardProps }
    | { type: 'SSDTrim'; props: SSDTrimCardProps }
    | { type: 'ThermalDashboard'; props: ThermalDashboardCardProps }
    | { type: 'MainFeature'; props: MainFeatureCardProps }
    | { type: 'DiskSpace'; props: DiskSpaceCardProps }
    | { type: 'Benchmark'; props: BenchmarkCardProps }
    | { type: 'Scanning'; props: ScanningCardProps }
    | { type: 'Uninstaller'; props: UninstallerCardProps }
}

组件不再是一个字符串,它是一个具有 2 个属性的对象,type一个字符串,props另一个对应的接口必须附加到该字符串值。

问题是现在我的 Record 类型不再工作了,这当然是正常的,因为组件不再是一个字符串,它是一个对象,所以我尝试了以下操作:

const components: Record<CardProps['component']['type'], React.ComponentType> {
  BatteryHealth: BatteryHealthComponent,
  DriveHealth: DriveHealthComponent,
  // ...
}

我的钥匙仍然在那里并且没有错误,但现在我使用这些组件的地方给了我一个错误:

Type '{ img: ImageContainerProps; icon: ImageContainerProps; } | 
      { img: ImageContainerProps; } | 
      { iconImg?: ImageContainerProps; description?: string; } | 
       ... 5 more ... | 
      { ...; }' is not assignable to type 'IntrinsicAttributes & { children?: ReactNode; }'.
  Type '{ img: ImageContainerProps; icon: ImageContainerProps; }' has no properties in common with type 'IntrinsicAttributes & { children?: ReactNode; }'.

当它只是组件的纯字符串名称时,一切正常,没有错误。

截图: http: //prntscr.com/1zb2yif

4

1 回答 1

0

操场

// define your props as a javascript array - don't forget "as const"
const props = [
{ type: 'BatteryHealth', props: 'some-props' },
{ type: 'DriveHealth', props: 'some-props' },
{ type: 'SSDTrim', props: 'some-props' },
{ type: 'ThermalDashboard', props: 'some-props' },
{ type: 'MainFeature', props: 'some-props' },
{ type: 'DiskSpace', props: 'some-props' },
{ type: 'Benchmark', props: 'some-props' },
{ type: 'Scanning', props: 'some-props' },
{ type: 'Uninstaller', props: 'some-props' },
] as const

// extract the props as a type
type CardProps = typeof props[number]

const components: Record<CardProps['type'], string> = {
  BatteryHealth: "foo",
  DriveHealth: "bar",
  InvalidComponent: "oh no" // error, as expected
}
于 2021-11-12T17:28:09.237 回答