簡體   English   中英

Dart中TypeScript的類型別名

[英]Type Aliases from TypeScript in Dart

是否可以在Dart中使用TypeScript中的類型?

樣本(TypeScript):

export type Speed = 'very slow' | 'slow' | 'normal' | 'fast' | 'very fast';

public getRealSpeed(speed: Speed): number {
    switch(speed) {
       ...
    }

    return 0;
} 

要么

public getRealSpeed(speed: 'slow' | 'fast' | 'unknown'): number {
    switch(speed) {
       //TODO
    }

    return 0;
} 

您可以將Dart枚舉用於相同的行為:

enum Speed { verySlow, slow, normal, fast, veryFast; }
int getRealSpeed(Speed speed) {
  switch (speed) {
    case Speed.verySlow: return 1;
    ...
    case Speed.veryFast: return 99;
  }
  return 0;
}

這確實意味着您必須將字符串值顯式轉換為Speed實例,也許使用

const speedByName = {
  "very slow": Speed.verySlow,
  "slow": Speed.slow,
  "normal": Speed.normal,
  "fast": Speed.fast,
  "very fast": Speed.veryFast,
};

暫無
暫無

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

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