【发布时间】: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属性的类型,所以我认为我在实现目标的正确方法上,但似乎不是 -
您作为答案发布的评论只会增加我的困惑。您定义一个类型,然后定义一个具有相同名称的泛型。这不是它的工作方式。您是否需要一个扩展您正在寻找的类型的泛型?请考虑编辑您的答案以添加您正在尝试执行的操作的有效示例。我觉得我可以解决你的问题,但我仍然不完全理解你在寻找什么。此外,可能使整个事情变得更容易的是为
CenteringOverlay和EnteringOverlay定义接口并拥有type Overlay = CenteringOverlay | EnteringOverlay | ...。
标签: javascript angular typescript