Last active
April 6, 2023 16:35
-
-
Save ciiqr/4e73678dec0b528d505282d2ed4e0087 to your computer and use it in GitHub Desktop.
typescript function parameter infer types between params
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
type LineItem = { | |
name: string, | |
quantity: number, | |
}; | |
type ObjectEntriesUnion<T extends Record<string, unknown>> = { | |
[K in keyof T]-?: { key: K, value: T[K] } | |
}[keyof T]; | |
type LineItemEntries = ObjectEntriesUnion<LineItem>; | |
// ^? type LineItemEntries = { key: "name"; value: string;} | { key: "quantity"; value: number;} | |
type UpdateAction = { type: 'updateLineItemValue' } & ObjectEntriesUnion<LineItem>; | |
function objectParam(req: LineItemEntries) { | |
if (req.key === 'name') { | |
console.log(req.value); // NOTE: CAN infer type here | |
// ^? (property) value: string | |
} | |
} | |
function separateParams<T extends UpdateAction, K extends T['key']>(reactKey: string, lineItemKey: K, value: Extract<T, { key: K }>['value']) { | |
if (lineItemKey === 'name') { | |
console.log(value); // NOTE: can't infer type here | |
// ^? (parameter) value: string | number | |
} | |
} | |
separateParams('', 'quantity', 0); | |
separateParams('', 'name', ''); | |
objectParam({ | |
key: 'name', | |
value | |
// ^? (property) value: string | |
}); | |
objectParam({ | |
key: 'quantity', | |
value | |
// ^? (property) value: number | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment