typescript

How to specify the types of a function so that the function can accept an object strictly only of type A or strictly only of type B


For example I have such function:

type A = {
    propA1: string
    propA2: string
}

type B = {
    propB1: string
    propB2: string
}

const f = (arg: A | B) => { }

then It can be used like this:

f({propA1: 'val', propA2: 'val', propB1: 'val'})

But I need an error in this case. I would like possibility passed argument with type only A, or only B, without mixing.

Playground


Solution

  • You can use overload signatures:

    type A = {
        propA1: string
        propA2: string
    }
    
    type B = {
        propB1: string
        propB2: string
    }
    
    function f(arg: A): void;
    function f(arg: B): void;
    function f(arg: A | B) { }
    
    f({propA1: 'val', propA2: 'val', propB1: 'val'})
    

    This causes a TypeScript error at build time.

    See example at TypeScript playground