Reputation: 2594
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
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