[英]Access to an optional attribute type of a typescript object
I have a class:我有一个 class:
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
}
};
...
}
I have an abstract class:我有一个抽象的 class:
abstract class AbstractParams<TParam> {
...
param: TParam
...
}
From this abstract class, I need to define specific classes for all style attribute within the overlay depending on the type
attribute value ('centering','entering').从这个抽象的 class 中,我需要根据
type
属性值('centering','entering')为覆盖层内的所有样式属性定义特定类。
So what I need to do is:所以我需要做的是:
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
}
And the same for entering:输入也一样:
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 }
}
More precisely, EnteringStyleParams and CenteringStyleParams objects will provide a style
to a Target Object, that's why I need them to have the same style
definition.更准确地说,EnteringStyleParams 和 CenteringStyleParams 对象将为目标 Object 提供
style
,这就是我需要它们具有相同style
定义的原因。
The easiest way to achive this is to explicitly define the types you need instead of typing Target.overlay
inline.实现这一点的最简单方法是显式定义您需要的类型,而不是内联输入
Target.overlay
。 This way you can use them both in the overlay and as the generics.通过这种方式,您可以在叠加层和 generics 中使用它们。 Your code could look something like this:
您的代码可能如下所示:
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']> { /* ... */ }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.