Home Upgrade Search Memberlist Extras Hacker Tools Award Goals Help Wiki Contact

Javascript 

Typescript type a function that returns different types based on input

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

¸„»°'´¸„»°'´Vorticalbox `'°«„¸`'°«„¸
`'°«„¸¸„»°'´¸„»°'´`'°«„¸Scientia Potentia est ¸„»°'´`'°«„¸`'°«„¸¸„»°'´
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)


Possibly Related Threads...
Thread / Author Replies Views Last Post
by emperorwurmJul 8, 2024 03:14 AM 7 203 Jul 8, 2024 03:14 AM
Last Post: emperorwurm
[PHP] by B00B5Jun 2, 2024 07:42 AM 12 475 Jun 2, 2024 07:42 AM
Last Post: SilentNuke
[PHP] by HardStoNSep 30, 2020 03:18 PM 32 386 Sep 30, 2020 03:18 PM
Last Post: Malthemar