You can just cast it to your union type:
const apiRoleArray = ["ADMIN", "USER"];
const realRoleArray: Role[] = <Role[]>apiRoleArray;
BUT you probably want to validate its contents rather than just trusting the API. :-) Drawing on this question's answers, you can create the type by using the keys of an object rather than defining it literally (see the accepted answer there for why):
const roleStrings = {
USER: "",
PRESENTER: "",
ORGANIZER: "",
ADMIN: ""
};
export type Role = keyof typeof roleStrings;
then give yourself a validation function:
const isRole = (s: string): s is Role => {
return roleStrings.hasOwnProperty(s);
};
then a robust conversion function, for example:
const rawToRoleArray = (rawArray: string[]): Role[] => {
return rawArray.map(s => {
if (!isRole(s)) {
throw new Error("Invalid Role: " + s);
}
return <Role>s;
});
};
(you could combine those if you don't need them separately)
then use it:
// Valid
const realRoleArray: Role[] = rawToRoleArray(["ADMIN", "USER"]);
console.log(realRoleArray);
// Invalid
const realRoleArray2: Role[] = rawToRoleArray(["ADMIN", "FOO"]);
console.log(realRoleArray2);
Live in the playground | Live on jsFiddle