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

0

Issue

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.

Solution

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,
  },
});

Answered By – jsejcksn

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave A Reply

Your email address will not be published.

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More