Búsqueda de sitios web

Interfaz de TypeScript con XOR, {bar:string} xor {can:number}


¿Cómo digo que quiero que una interfaz sea una u otra, pero no ambas ni ninguna?

interface IFoo {
    bar: string /*^XOR^*/ can: number;
}

Respuesta #1

Puedes usar tipos de unión junto con el tipo never para lograr esto:

type IFoo = {
  bar: string; can?: never
} | {
  bar?: never; can: number
};


let val0: IFoo = { bar: "hello" } // OK only bar
let val1: IFoo = { can: 22 } // OK only can
let val2: IFoo = { bar: "hello",  can: 22 } // Error foo and can
let val3: IFoo = {  } // Error neither foo or can

Respuesta #2

Como se propone en este tema, puedes usar tipos condicionales (introducidos en Typescript 2.8) para escribir un tipo XOR:

type Without<T, U> = { [P in Exclude<keyof T, keyof U>]?: never };
type XOR<T, U> = (T | U) extends object ? (Without<T, U> & U) | (Without<U, T> & T) : T | U;

Y puedes usarlo así:

type IFoo = XOR<{bar: string;}, {can: number}>;
let test: IFoo;
test = { bar: "test" } // OK
test = { can: 1 } // OK
test = { bar: "test",  can: 1 } // Error
test = {} // Error

Artículos relacionados