If you wish to convert it to your union type, follow this method:
const apiRoleArray = ["ADMIN", "USER"];
const realRoleArray: Role[] = <Role[]>apiRoleArray;
However, it is advisable to validate its contents rather than solely relying on the API. :-) Utilizing the insight provided in this question's responses, you can define the type by referencing the keys of an object instead of explicitly declaring it (refer to the accepted solution there for clarification):
const roleStrings = {
USER: "",
PRESENTER: "",
ORGANIZER: "",
ADMIN: ""
};
export type Role = keyof typeof roleStrings;
Establish a validation function as follows:
const isRole = (s: string): s is Role => {
return roleStrings.hasOwnProperty(s);
};
Then create a robust conversion function, such as:
const rawToRoleArray = (rawArray: string[]): Role[] => {
return rawArray.map(s => {
if (!isRole(s)) {
throw new Error("Invalid Role: " + s);
}
return <Role>s;
});
};
(you can combine these functions if needed)
Finally, put them into action:
// Valid
const realRoleArray: Role[] = rawToRoleArray(["ADMIN", "USER"]);
console.log(realRoleArray);
// Invalid
const realRoleArray2: Role[] = rawToRoleArray(["ADMIN", "FOO"]);
console.log(realRoleArray2);
Try it out in the playground | Test it on jsFiddle