TypeScript函数接受枚举中的参数值

时间:2015-09-17 10:05:50

标签: enums typescript

下面的代码,参数genderenum type,值必须是["male","female"]之一,但我想像judgeGender("male")一样使用它,我该怎么办?做了?

function judgeGender(gender){
    //......
}

3 个答案:

答案 0 :(得分:1)

你可以做的是接受一个字符串和check that it exists in the Enum,如下所示:

enum Gender {Male, Female};

function validGender(c: String) {
    if(enumHasValue(Gender, c)) {
        document.write(`valid gender: ${c}`);
    } else {
        document.write(`invalid gender: ${c}`);
    }
}

function enumHasValue(e, v) {
    for (var enumMember in e) {
        if (enumMember === v) {
            return true;
        }
    }
    return false;
}

validGender("Female"); // => "valid gender: Female"
document.write("<br/>");
validGender("Alien"); // => "invalid gender: Alien"

TypeScript Playground中试用此示例(复制并粘贴,然后按运行)。

答案 1 :(得分:1)

您可以创建一个解析gender参数的函数,如下所示:

function parseGender(value : Gender | number | string) {
  var gender;
  if (value === Number(value)) {
    gender = <Gender>value;
  }
  else if (value === String(value)) {
    if (<string>value in Gender) {
      gender = Gender[value];
    }
  }

  if (!gender) throw new TypeError("The parameter gender is incorrect");
  return gender;
}

然后你可以在你的功能中使用它:

function judgeGender(gender : Gender | number | string) {
  var g = parseGender(gender);

  // do whatever you want with g
}

答案 2 :(得分:1)

您可以指定您的功能可以接收的值。

type Male = "male";
type Female = "female";

enum Gender {
    Male = Male,
    Female = Female
}

function judgeGender(gender: Gender | Male | Female) {
    //......
}

judgeGender(Gender.Male);
judgeGender("male");