Home > Enterprise >  Trying to implement a function that takes two out of three possible types of arguments
Trying to implement a function that takes two out of three possible types of arguments

Time:10-08

I have three different types

type A = 'a'
type B = 'b'
type C = 'c'

I want to type a function either accepts A, C or B, C but not A, B, and C.

Here is my attempt

type A = 'a'
type B = 'b'
type C = 'c'
type BaseArgs = {
    c: C
}
type VariantA = {
    a: A
} & BaseArgs

type VariantB = {
    b: B,
} & BaseArgs

function fn(arg: VariantA | VariantB) {
}

But turns out it doesn't work as expected, as

const b: B = 'b'
const a: A = 'a'
const c: C = 'c'

fn({b,a,c})  // this would not error out

fn({b,a,c}) should be giving an error but it is not.

CodePudding user response:

{a:A, b:B, c:C} matches the union of your acceptable types.

use an overload to specify you only want one or the other:

function fn(arg: VariantA): void;
function fn(arg: VariantB): void;
function fn(arg: VariantB | VariantA) {
}

typscript playground

CodePudding user response:

Seems like TypeScript is being nice here--the object is both a valid VariantA or VariantB so it allows it, despite having an extra variable if you were to "choose" just one or the other. If you don't want this, you could specify explicitly:

type VariantA = {
    a: A;
    b?: never; // This line!
} & BaseArgs

(and do the same for VariantB)

  • Related