Search code examples
typescriptinterface

types that are assignable to type 'never'


In the following example, does anyone know how to write the field variable such that it complies with the given interfaces (and thus we shouldn't have to change the interfaces)? Right now I am getting an error saying Type '{ accountId: string; active: true; }[]' is not assignable to type 'never'.

interface Fields {
    votes: Votes & {
        voters: never;
    };
}

interface Votes {
    self: string;
    votes: number;
    hasVoted: boolean;
    voters: User[];
}

interface User {
    accountId: string;
    active: boolean;
}

const field: Fields = {
    votes: {
        self: "self",
        votes: 0,
        hasVoted: false,
        voters: [
            {
                accountId: "accountId",
                active: true,
            },
        ],
    },
};

Solution

  • Nothing is assignable to never, so you'll have to force it with a type assertion. For example:

    const fields: Fields = {
        votes: {
            self: "self",
            votes: 0,
            hasVoted: false,
            voters: [
                {
                    accountId: "accountId",
                    active: true,
                },
            ] as Fields["votes"]["voters"], // <=============
        },
    };
    

    Playground link