Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript Conditional Inside TypeScript Interface

Is it possible to have a condition inside of an interface declaration in TypeScript. What I'm looking for is a way to say, based on the value of the first key, the second key can be these values.

Example (non functioning):

interface getSublistValue {

    /** The internal ID of the sublist. */
    sublistId: 'item' | 'partners';

    /** The internal ID of a sublist field. */
    if (this.sublistId === 'item') {
        fieldId: 'itemname' | 'quantity';
    }

    if (this.sublistId === 'partners') {
        fieldId: 'partnername' | 'location';
    }
}
like image 939
Jon Lamb Avatar asked Sep 05 '25 03:09

Jon Lamb


1 Answers

No there's not. The best thing to do is to create separate interfaces that describe the two different types of data.

For example:

interface SublistItem {
    sublistId: 'item';
    fieldId: 'itemname' | 'quantity';
}

interface SublistPartners {
    sublistId: 'partners';
    fieldId: 'partnername' | 'location';
}

function getData(): SublistItem | SublistPartners {
    return (Math.random() < 0.5)
        ? { sublistId: 'item', fieldId: 'itemname' }
        : { sublistId: 'partners', fieldId: 'partnername' };
}

const someValue = getData();

if (someValue.sublistId === "item") {
    // SublistItem in here
}
else {
    // SublistPartners in here
}
like image 176
David Sherret Avatar answered Sep 07 '25 19:09

David Sherret