Home > Software design >  How to infer the type of a property based on another property
How to infer the type of a property based on another property

Time:01-23

I'm trying to get a property to infer its types based on the value of its sibling property. For example, I have two types, a Base type and an Extended type. There are some properties in the Base type that also exists in the Extended type.

type Base = {
  key1: string;
  key2: string;
  key3: string;
}

type Extended = {
  key1: { prop1: string; prop2: string };
  key2: { prop1: string };
}

Now, I have another type Test that has two properties, the name and value. If the name property is one of the keys in the Extended type, the value property should be the keys associated to the type in the Extended type, else, the value property should not be passed. This is what I've made so far.

type Test<T = keyof (Base & Extended)> = {
  name: T;
  value?: T extends keyof Extended ? (keyof Extended[T])[] : never
}

const test: Test = {
  name: 'key1',
  value: ['']
}

However, this does not work. Whatever name prop you pass still allows you to input both prop1 and prop2 string literals. The case should be that if the name is 'key1', it should be able to accept an optional array of strings, and the strings should be the properties defined in the Extended type. Moreover, if the name is key3, the value property should never exist.

Thank you for any help.

CodePudding user response:

I'm not sure if understood correctly. Does this meet your requirements:

type Test2<T = keyof (Base & Extended)> = T extends keyof Extended ? {
  name: T;
  value?: (keyof Extended[T])[]
} : {
  name: T
}
  • Related