1

Say I have an object type like:

interface Thing {
  a: number;
  b: string;
}

Can Typescript automatically derive a function type from it?

function signatureDerivedFromThing(a: Thing["a"], b: Thing["b"]) {
  // typeof signatureDerivedFromThing is ???<Thing>
};

Second question: Is the reverse possible?

I'm aware of the caveats of valid identifier names vs valid object keys, the unclear order of arguments, and the unspecified return type. I'm bridging the gap between value space and type space. But still. Is this possible?

Note that I don't want a function with 1 argument of type Thing, which would be rather straightforward with destructuring parameter assignment.

Rest parameters with value type ...rest: Thing[keyof Thing][] is a step closer to my idea. But then I'm missing the number of arguments and their names.

Parameters<T> seems almost enough for declaring object keys from a function signature, though labeled tuples does not seem quite enough to achieve that. I also didn't find any counterpart going from keys to function args.

I just cannot make the final leap from key name to argument name.

Arthur_J
  • 66
  • 5
  • 1
    Unfortunately this is not possible for the reasons laid out in the answers to the other questions here. Tuple labels are not observable to the type system, and object key order is also not observable to the type system. – jcalz Feb 20 '23 at 21:55
  • @jcalz Thank you. While every similar question concerns itself with the other way around (parameters to object) the same limitation seams to apply. Technically my question might be different, but I leave it closed. – Arthur_J Feb 21 '23 at 09:37

0 Answers0