Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript reference self object keys

I'm trying to build a typescript type which can infer current object's keys and put them as argument of the selfMethod function. Is it possible to reference keys of the current object ? I know self-referencing is not supported in Typescript yet but I believe it doesn't perform infinite recursion, as such was hoping for a solution.

const obj = {
    act1(selfMethods) {
        return 1;
    },
    act2(selfMethods) {
        // Intellisense should say "return type is number" amd only allow "act1" | "act2" as possible argument of selfMethods
        return selfMethods('act1');
    }
}

Given something like (replacing Self with something:

type SelfKeysReference = {[key: string]: (selfMethods: <K extends keyof Self>(key: K) => ReturnType<Self[K]>) => any}

Thanks for your help!

like image 655
ovesco Avatar asked Jan 01 '26 11:01

ovesco


1 Answers

Adding details for the person asking in comment. I could not find a solution as it is and managed to do it in another way. I tried again today but the closer I came to was by doing something like that:

type CircularFn = <Obj extends Record<string, <K extends keyof Obj>(key: K) => K>>(
  item: Obj,
) => Obj;

const fn: CircularFn = val => val;

const test = fn({
  a: k => k,
  b: k => k,
});

test.b('a');

Which raises a circular constaint error but somewhat works.

like image 62
ovesco Avatar answered Jan 03 '26 12:01

ovesco



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!