【问题标题】:Access to an optional attribute type of a typescript object访问 typescript 对象的可选属性类型
【发布时间】:2022-01-22 18:53:24
【问题描述】:

我有一堂课:

 class Target {
  ...
  readonly overlay: {
    type: 'none'
   } | {
    type: 'centering',
    style?: {
      color?: string,
      offset?: number,
      size?: number,
    }
   } | {
    type: 'entering',
    style?: {
      color?: string,
      offset?: number,
      direction?: 'up' | 'down',
      angle?: number,
      size?: number
    }
  };
  ...
 }

我有一个抽象类:

 abstract class AbstractParams<TParam> {
  ...
  param: TParam
  ...
 }

从这个抽象类中,我需要为所有定义特定的类 覆盖层内的样式属性取决于type 属性值('centering','entering')。

所以我需要做的是:

type CenteringStyleType = // Type of style attribute within overlay when its attribute `type` equals to `centering`.

class CenteringParams extends AbstractParams<CenteringStyleType> {
 // Here the param attribute would have type:  { color?: string, offset?: number, size?: number }
 // And then I can use it
}

输入也一样:

type EnteringStyleType = // Type of style attribute within overlay when its attribute `type` equals to `entering`.

class EnteringParams extends AbstractParams<EnteringStyleType> {
 // Here the param attribute would have type:  { color?: string, offset?: number, size?: number }
}

更准确地说,EnteringStyleParams 和 CenteringStyleParams 对象将为目标对象提供 style,这就是为什么我需要它们具有相同的 style 定义。

【问题讨论】:

  • 我不完全明白你的目标是什么。我不明白Target 是什么以及你想用它做什么。您的目标是否只是根据overlay.type 的值访问overlay.style 中的相应属性?
  • 是的,是的! Target 是其中的类,其中是覆盖属性。我尝试将您提到的内容访问到另一个课程中
  • 访问是指你想在运行时访问它,或者你想为它定义一个类型?我不明白你对type CenteringOffset = Target['offset'] 行的目标是什么。你能更详细地解释一下吗?如果Target 是拥有overlay 属性的类,那么Target['offset'] 是什么?你从来没有定义过。
  • 我需要访问类 Target 的 overlay 属性中的 style 属性的类型,具体取决于 type 属性的值。我需要访问此类型以将其用作泛型类型来构建另一个类。 Target['offset'] 只是一个尝试,它给出了 offset 属性的类型,所以我认为我在实现目标的正确方法上,但似乎不是
  • 您作为答案发布的评论只会增加我的困惑。您定义一个类型,然后定义一个具有相同名称的泛型。这不是它的工作方式。您是否需要一个扩展您正在寻找的类型的泛型?请考虑编辑您的答案以添加您正在尝试执行的操作的有效示例。我觉得我可以解决你的问题,但我仍然不完全理解你在寻找什么。此外,可能使整个事情变得更容易的是为CenteringOverlayEnteringOverlay 定义接口并拥有type Overlay = CenteringOverlay | EnteringOverlay | ...

标签: javascript angular typescript


【解决方案1】:

实现这一点的最简单方法是显式定义您需要的类型,而不是在行内键入Target.overlay。这样您就可以在叠加层和泛型中使用它们。您的代码可能如下所示:

interface CenteringStyleType {
  type: 'centering',
  style?: {
    color?: string,
    offset?: number,
    size?: number,
  }
}

interface EnteringStyleType { /* ... */ }
interface NoneStyleType { /* ... */ }

class Target {
  readonly overlay: CenteringStyleType | EnteringStyleType | NoneStyleType;
}

class CenteringParams extends AbstractParams<CenteringStyleType['style']> { /* ... */ }


【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-25
    • 1970-01-01
    • 2021-02-05
    • 1970-01-01
    • 2023-03-29
    • 2017-08-31
    相关资源
    最近更新 更多