TypeScript function accept argument value from an enum
下面的代码,参数
1 2 3 | function judgeGender(gender){ //...... } |
您可以指定函数可以接收哪些值。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | type Male ="male"; type Female ="female"; enum Gender { Male = Male, Female = Female } function judgeGender(gender: Gender | Male | Female) { //...... } judgeGender(Gender.Male); judgeGender("male"); |
您可以创建一个函数来解析
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | 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; } |
然后你可以在你的函数中使用它:
1 2 3 4 5 | function judgeGender(gender : Gender | number | string) { var g = parseGender(gender); // do whatever you want with g } |
您可以接受一个字符串并检查它是否存在于枚举中,如下所示:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | 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操场中尝试这个例子(复制并粘贴它,然后按run)。