简体   繁体   中英

Access to an optional attribute type of a typescript object

I have a 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:

 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').

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.

The easiest way to achive this is to explicitly define the types you need instead of typing Target.overlay inline. This way you can use them both in the overlay and as the 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']> { /* ... */ }


The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM