簡體   English   中英

Typescript 接口 + 常量與 class 用於定義類似枚舉的 object

[英]Typescript interface + constants vs class for defining enum-like object

我是 typescript 的新手,我正在嘗試定義一個帶有一些附加屬性的類似枚舉的 class。 我已經看到有兩種不同的方法可以做到這一點:

  1. 使用 class,類似於我在 Java 中所做的:
export class AwsRegion {
 
     public static US_EAST_1 = new AwsRegion('us-east-1');
     public static EU_WEST_1 = new AwsRegion('eu-west-1');
     public static US_WEST_2 = new AwsRegion('us-west-2');
 
     private name: string;
 
     constructor(name: string) {
         this.name = name;
     }
 
     public getName(): string {
         return this.name;
     }
 }

  1. 使用接口 + typescript 常量:
 export interface AwsRegion {
     readonly name: string;
 }

export const US_EAST_1: AwsRegion = { name: 'us-east-1' };
export const EU_WEST_1: AwsRegion = { name: 'eu-west-1' };
export const US_WEST_2: AwsRegion = { name: 'us-west-2' };

兩者中的任何一個有什么優勢,或者在 typescript 中比另一個更慣用嗎?

謝謝,

Typescript 支持大量編程 styles。 要了解 AWS 團隊為 CDK 選擇的習語,請查看CDK github 源代碼 lambda package源是一個很好的起點。

CDK經常使用static工廠方法進行配置:

export class Runtime {
  // ...
  public static readonly NODEJS_14_X = new Runtime('nodejs14.x', RuntimeFamily.NODEJS, { supportsInlineCode: true });
  public static readonly PYTHON_2_7 = new Runtime('python2.7', RuntimeFamily.PYTHON, { supportsInlineCode: true });

關於您的示例,請注意,正如所寫,這兩種方法都允許調用者創建無效的配置對象。 Typescript 將無怨無悔地接受mars作為區域:

// class
const mars: AwsRegion = new AwsRegion('mars');

// plain old object
const MARS_REGION: AwsRegion = { name: 'mars' };

你可以解決這個問題。 對於 class 方法:將構造函數設為私有。

private constructor(name: string) {} 

// TS Error: Constructor of class 'AwsRegion' is private and only accessible within the class declaration
const mars: AwsRegion = new AwsRegion("mars")

對於 POJO 版本,縮小界面中的有效區域

interface AwsRegion {
  readonly name: 'us-east-1' | 'eu-west-1' | 'us-west-2';
}

// TS Error:  Type '"mars"' is not assignable to type '"us-east-1" | "eu-west-1" | "us-west-2"'
const MARS_REGION: AwsRegion = { name: 'mars' };

這是這些示例的 TS Playground 實時代碼版本

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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