Skip to content

Instantly share code, notes, and snippets.

@Shrugsy
Last active April 3, 2021 07:14
Show Gist options
  • Save Shrugsy/8e62b0cb2855508ec84e58e16ea5a419 to your computer and use it in GitHub Desktop.
Save Shrugsy/8e62b0cb2855508ec84e58e16ea5a419 to your computer and use it in GitHub Desktop.
Type Narrowing Identify Function example
type ComparisonFn = (left: number, right: number) => boolean;
// `buildComparison` is a 'Type Narrowing Identity Function'
// It returns the value given to it, but also narrows the types.
// In this case it allows typescript to retain the literal types of the keys
// rather than widening them to 'string'
const buildComparisons = <Comparison extends Record<string, ComparisonFn>>(comparison: Comparison) => comparison;
// Using the Type Narrowing Identity Function:
const comparisons = buildComparisons({
'=': (left, right) => left === right,
'≠': (left, right) => left !== right,
'>': (left, right) => left > right,
'<': (left, right) => left < right,
'≥': (left, right) => left >= right,
'≤': (left, right) => left <= right,
});
type Operator = keyof typeof comparisons;
function compare(left: number, operator: Operator, right: number): void {
const result = comparisons[operator](left, right);
console.log(`${left} ${operator} ${right} ? ${result}`)
}
compare(2, '=', 6);
compare(2, '=', 2);
compare(2, '<', 6);
compare(6, '<', 2);
compare(2, '>', 6);
compare(6, '>', 6);
compare(6, '>', 2);
compare(-5, '=', 6);
compare(-5, '=', -5);
compare(0, '>', 6);
compare(0, '>', 0);
compare(0, '≥', 6);
compare(0, '≤', 6);
compare(0, '≠', 0);
compare(2, '≠', 2);
compare(1, '≠', 3);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment