0

I'm trying to create a config object that can be of multiple interfaces, but I want to restrict to exactly one. So, for example:

interface A {
    firstName: string;
    lastName: string;
}

interface B {
    username: string;
}

interface C {
    token: string;
}

interface D {
    role: string;
}

type Config = A | B | C | D;

Say if I'm trying to create a general logging function that will take that config object where I will need to access those properties, but not sure which interface is getting passed in:

function logConfig(config: Config) {
    const { firstName, lastName, username, token, role } = config;

    if (firstName & lastName) {
        // Do this
    }

    if (username) {
        // Do this
    }

    if (token) {
        // Do this
    }

    if (role) {
        // Do this
    }

}

but problem is not all of those properties will exist. is only way to do this is to use the optional & never method?

So my interfaces would have to look like this instead?

interface A {
    firstName: string;
    lastName: string;
    username?: never;
    token?: never;
    role?: never;
}

interface B {
    username: string;
    firstName?: never;
    lastName?: never;
    token?: never;
    role?: never;
}

interface C {
    token: string;
    username?: never;
    firstName?: never;
    lastName?: never;
    role?: never;
}

interface D {
    role: string;
    username?: never;
    firstName?: never;
    lastName?: never;
    token?: never;
}

rog824
  • 11
  • 3

0 Answers0