How to get the type of a key's value from an interface?

Viewed 25

I have TS interface like:

MyInterface {
  'key1': number | string;
  'key2': string;
  'key3': SomeOtherInterface;
}

I want to create a new type that uses the properties of MyInterface:

MyType<K = keyof MyInterface> = {
  'key': K;
  'value': MyInterface[K];
  'somethingElse': string
}

What I'm trying to achieve is that if the key of MyType is 'key1', the value must be of type number | string, and if the key is 'key2' the value must be of type string and so on. But my attempt above leads to an error: Type 'K' cannot be used to index type 'MyInterface'. How should I define MyType?

1 Answers
var indexedArray: { [key: string]: number } = {
    foo: 2118,
    bar: 2118
}

indexedArray['foo'] = 2118;
indexedArray.foo = 2118;

let foo = indexedArray['myKey'];
let bar = indexedArray.myKey;
Related