Home > Blockchain >  Infer possible values from a key within an interface
Infer possible values from a key within an interface

Time:08-03

I want to infer the possible values for the value property, depending on the key. For example, if the key is name, the value should be a string. If the key is age, the value should be a number. The way it is now, we can correctly choose a key, but no matter what the key is - the value is either string or number (it takes all possible values due to MainEntity[keyof MainEntity]. How can I infer only the possible values for the specific key?

interface Example<MainEntity> {
  key: keyof MainEntity;
  data: {
    value: MainEntity[keyof MainEntity];
  };
}

interface Entity {
  name: string;
  age: number;
}

const fn = (obj: Example<Entity>) => {};
fn({ key: 'name', data: { value: '14' } });

CodePudding user response:

You need to link key to data.value so something like this

interface Example<MainEntity, K extends keyof MainEntity> {
  key: K;
  data: {
    value: MainEntity[K];
  }
}
      
interface Entity {
  name: string;
  age: number;
}
      
const fn = <K extends keyof Entity>(obj: Example<Entity, K>) => {};
fn({ key: 'name', data: { value: '14' } });

fn can also be defined like this

const fn = (obj: {[K in keyof Entity]: Example<Entity, K>}[keyof Entity]) => {};
  • Related