Use one interface out of many for params in function

Viewed 51

I have a function like this:

interface Interface1 {
    one: string
}
interface Interface2 {
    two: string
}
interface Interface3 {
    three: string
}
type ManyInterfacesInOneType = Interface1 | Interface2 | Interface3;

function bla(param1: ManyInterfacesInOneType) {

}

When I try to use the function like this and I call the function like bla({...}), it lets me put variables from all the interfaces, but I want the function to be limited to one out of many. So I don't want this to happen:

bla({one: '', two: '', three: ''});

I also tried doing:

function bla<T extends object>(param1: T) {

}

But this doesn't make the generic type required, so it doesn't even really help.

Any ideas how I can make this work?

1 Answers

It is possible to do with small helper:

interface Interface1 {
    one: string
}
interface Interface2 {
    two: string
}
interface Interface3 {
    three: string
}
type Union = Interface1 | Interface2 | Interface3;

// credits goes to https://stackoverflow.com/questions/65805600/type-union-not-checking-for-excess-properties#answer-65805753
type UnionKeys<T> = T extends T ? keyof T : never;
type StrictUnionHelper<T, TAll> =
    T extends any
    ? T & Partial<Record<Exclude<UnionKeys<TAll>, keyof T>, never>> : never;

type StrictUnion<T> = StrictUnionHelper<T, T>


function bla<T extends Union,>(param1: StrictUnion<Union>) {

}

bla({ one: 'one' }) // ok
bla({one:'one', two:'two'}) // error

Playground

Here, in my blog, you can find more examples of utility types which are useful in practice, because all of them are taken from here (stackoverflow)

Related