下面的代码,参数gender
为enum type
,值必须是["male","female"]
之一,但我想像judgeGender("male")
一样使用它,我该怎么办?做了?
function judgeGender(gender){
//......
}
答案 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");