Hack Forums
[Javascript] Typescript type a function that returns different types based on input - Printable Version

+- Hack Forums (https://hackforums.net)
+-- Forum: Tech (https://hackforums.net/forumdisplay.php?fid=444)
+--- Forum: Coding (https://hackforums.net/forumdisplay.php?fid=151)
+---- Forum: Web Development (https://hackforums.net/forumdisplay.php?fid=183)
+---- Thread: [Javascript] Typescript type a function that returns different types based on input (/showthread.php?tid=6104230)



Typescript type a function that returns different types based on input - vorticalbox - Aug 21, 2020

I am creating a function that takes a path, a value and optionally an object that will find the path in the object and return if it matches the value, my problem is i am having a hard time typing this.

 

PHP Code

<?php 
import 
* as R from 'ramda';
export type PropEqCurry = (obj: any) => boolean
export type PropEqCall 
=  boolean
export type PropEq 
= PropEqCurry | PropEqCall

export 
const propEq = (path: string, value: any, obj?: Object): PropEq => (obj
  
? R.equals(pick(path, obj), value)
  : (obj: any) => R.equals(pick(path, obj), value)); 

 
however, this requires me to set the type when using it which I don't like

PHP Code

<?php 
const checkName = propEq('name', 'jest') as PropEqCurry; 

I would like to return type to be inferred from the arguments passed


RE: Typescript type a function that returns different types based on input - SIM-1517830 - Aug 22, 2020

Maybe this can help?
Code
export type PropEqCurry = (obj: any) => boolean
export type PropEqCall =  boolean
export type PropEq = PropEqCurry | PropEqCall
export type ReturnType = 'Call' | 'Curry'

function propEq(type: 'Call', path: string, value: any, obj?: Object): PropEqCall
function propEq(type: 'Curry', path: string, value: any, obj?: Object): PropEqCurry
function propEq(type: ReturnType, path: string, value: any, obj?: Object): PropEq {
switch (type) {
     case 'Curry': {
         return (obj: any) => !!'Monster Energy' // R.equals(pick(path, obj), value))
     }
     case 'Call':
     default: {
        return !!'Monster Energy' // R.equals(pick(path, obj), value))
     }
}
}

var a = propEq('Call', 'somePath', 'scomeValue')
console.log(typeof a) // boolean (i.e. PropEqCall)

var b = propEq('Curry', 'somePath', 'someValue', { some: 'object'})
console.log(typeof b) // function (i.e. PropEqCurry)