Amol Gupta
Amol Gupta

Reputation: 2594

Typescript Unions for object type

Is there a way to achieve something similar.

It is not possible to call someFunction in the if statement as key and value are used between the if statement and someFunction call.

type someObj = {
    a: string,
    b: number
};

type someObjType = { [K in keyof someObj]: { prop: K, value: someObj[K] } }[keyof someObj];

function someFunction(args: someObjType) {

};

function someOtherFunction() {
    let key: someObjType['prop'],
        value: someObjType['value'];
    if (Math.random() > .5) {
        key = 'a',
            value = 'some String'
    } else {
        key = 'b';
        value = 200
    };

    // Do Something using key and value.

    someFunction({ prop: key, value }) // throws an error.
};

Upvotes: 0

Views: 64

Answers (1)

Matt McCutchen
Matt McCutchen

Reputation: 30999

Could you just go ahead and create an object of type someObjType in the if statement and then use obj.prop and obj.value instead of key and value?

function someOtherFunction() {
    let obj: someObjType;
    if (Math.random() > .5) {
        obj = {
            prop: 'a',
            value: 'some String'
        };
    } else {
        obj = {
            prop: 'b',
            value: 200
        };
    };

    // Do Something using obj.prop and obj.value.

    someFunction(obj)
};

Upvotes: 1

Related Questions