简体   繁体   English

对象类型的Typescript并集

[英]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. 不能在if语句中调用someFunction,因为在if语句和someFunction调用之间使用了键和值。

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.
};

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 ? 您能否继续在if语句中创建类型为someObjType的对象,然后使用obj.propobj.value代替keyvalue

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)
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM