Home > Software engineering >  How do you properly infer the key of an index signature?
How do you properly infer the key of an index signature?

Time:03-15

I've been struggling with generic mapped inferred types in TypeScript, quite possibly I'm overcomplicating things but I basically have a function that returns an object with the same keys as the input object, but with each value mapped (via a function). I created a standalone sandbox to show the issue in one file:

https://codesandbox.io/s/typescript-playground-export-forked-s6jwzn?file=/index.ts

Summary of code:

const factories = {
  type1: function createInstance1(instance1Properties: Type1Props): Type1Instance { /* ... */ },
  type2: function createInstance2(instance2Properties: Type2Props): Type2Instance { /* ... */ }
}

// example input for function
const input = {
  type1: { /* valid Type1Props */ },
  // no type2 here
}

// expected output shape
const output = {
  type1: { /* valid Type1Instance */ },
  // no type2 here, matching input
}

The function implementation itself is trivial, but I haven't figured out how to implement the function's type signature. I would appreciate any assistance/advice!

CodePudding user response:

I don't think I understand completely your problem, but I will give it a try.

A function that returns an object with the same keys as the input object, but with each value mapped (via a function).

So you have a type of the input and another for the output, with the same keys but different prop types:

type Input = {
  type1: Type1Prop,
  type2: Type2Prop
}

type Output = {
  type1: Type1Instance,
  type2: Type2Instance
}

The function needed would be defined as follows:

function someFunction(input: Input): Output {
  // Do the mapping
}

If you want to explicitly define its type, you would use an assigned function:

type someFunctionType = (input: Input) => Output;

let someFunction: someFunctionType = (input) => {
  // Do the mapping
}

If this doesn't help, can you elaborate in this example please?

CodePudding user response:

I sort of accomplished what I want with an intermediate function that takes a list of types (e.g. ['type1']) and returns a new function that works mostly the way I want. I updated the playground at https://codesandbox.io/s/typescript-playground-export-forked-s6jwzn?file=/index.ts in case someone finds it helpful, or has a way to do what I originally wanted (no wrapper function). There are also a couple of things that don't quite work right in what I did (referenced in the code comments), so any suggestions to fix those would be greatly appreciated!

  • Related