Home > other >  How to describe the generic parameters of a map where the key is a property of the value?
How to describe the generic parameters of a map where the key is a property of the value?

Time:11-20

How can one specify the generic parameters of a Map such that the each key is mapped to a value that contains the key as a value for the specific property. If that's not clear, here is an example:

const example = {
  'a': {
    specialKey: 'a',
    aField: 'specific thing to a'
  },
  'b': {
    specialKey: 'b',
    bField: 'specific thing to b'
  }
}

In the above example, I want to capture that for the value for key a, specialKey has value a.

CodePudding user response:

You can use an identity function to enforce the kind of key-value type relationship described in your question.

TS Playground link

function validMap <T extends {
  [K in keyof T]: K extends string ? { specialKey: K } : never;
}> (value: T): T {
  return value;
}

const map1 = validMap({
  a: {
    specialKey: 'a',
  },
  b: {
    specialKey: 'b',
    stringProp: 'foo',
    numberProp: 42,
  },
});

const map2 = validMap({
  a: {
    specialKey: 'a',
  },
  b: {
    specialKey: 'c',
//  ^^^^^^^^^^
// Type '"c"' is not assignable to type '"b"'.(2322)
    stringProp: 'foo',
    numberProp: 42,
  },
});
  • Related