Búsqueda de sitios web

javascript - Angular 6 - Cómo definir el tipo de valor de retorno con más de 1 tipo


Tengo una función de retorno en Angular 6, y quiero definir el tipo de valor de retorno. Pero el problema es que mi función puede ser utilizada en varios casos, y el valor de retorno depende del caso. Aquí está mi código a continuación:

updateProcess(type, list, event: {}) {
    let newList = [];
    switch (event["action"]) {
        case ListManipulation.Add:
            newList = list;
            newList.push(event["data"]);
            break;
        case ListManipulation.Delete:
            newList = list.filter(
                setting => !event["data"].includes(setting[this.itemProperties[type]["idName"]])
            );
            break;
        default:
            newList = list;
            break;
    }
    return [...newList];
}

y supongamos que tienes un tipo para el valor de retorno, puedes hacerlo así:

updateProcess(type, list, event: {}): string {

Pero lo que quiero hacer es:

updateProcess(type, list, event: {}): string | [] | {} {

¿Alguien puede ayudar?

PD. También necesito eso para el tipo de lista como parámetro

Respuesta #1

Puedes crear un tipo basado en todos los demás tipos y usarlo como un tipo normal

type specialType = string  | {} | any[];

y úsalo así

updateProcess(type, list : specialType , event: {}) : specialType   {
    let newList = [];
    switch (event["action"]) {
        case ListManipulation.Add:
            newList = list;
            newList.push(event["data"]);
            break;
        case ListManipulation.Delete:
            newList = list.filter(
                setting => !event["data"].includes(setting[this.itemProperties[type]["idName"]])
            );
            break;
        default:
            newList = list;
            break;
    }
    return [...newList];
}