簡體   English   中英

訪問 typescript object 的可選屬性類型

[英]Access to an optional attribute type of a typescript object

我有一個 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
    }
  };
  ...
 }

我有一個抽象的 class:

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

從這個抽象的 class 中,我需要根據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 對象將為目標 Object 提供style ,這就是我需要它們具有相同style定義的原因。

實現這一點的最簡單方法是顯式定義您需要的類型,而不是內聯輸入Target.overlay 通過這種方式,您可以在疊加層和 generics 中使用它們。 您的代碼可能如下所示:

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM