0

I'm trying to make a primary row Id constraint right now for some generic forms I'm making. I need a constraint that allows people to specify the name of the property on T, such that the value is of type z. I'll explain in more detail.

Constraint should basically mean, "give me the name of any property on type T where the value of T[propertyName] is of type V."

The important thing here is to make it work with generics. Also... to allow accessing properties via the property key afterwards.

interface Model {
  text?: string;
  id: number;
  uniqueId: string;
}

interface SomeProps<T> {
  model: T;
  primaryKey: KeyOfType<Model, number>; 
}

function testFunction(props: SomeProps<Model>) {
   console.log('The primary key is: '+ props.model[props.primaryKey]); // 99
}

testFunction({ model: { id: 99, text: 'hello universe', uniqueId: 'ssfwe3234'}, primaryKey: 'id'});
Pangamma
  • 731
  • 12
  • 28
  • 1
    See the `KeysMatching` type defined here: [How to write PickByValue type?](https://stackoverflow.com/questions/55150760/how-to-write-pickbyvalue-type) – kaya3 Jan 02 '21 at 21:17
  • 1
    Does this answer your question? [Restrict generic key type based on lookup type in TypeScript](https://stackoverflow.com/questions/65241412/restrict-generic-key-type-based-on-lookup-type-in-typescript) (The `Filter` type in the accepted answer) – Henry Woody Jan 02 '21 at 21:18
  • I actually got it to work using the KeyOfType solution presented here. https://stackoverflow.com/a/60206860/1582837 I'm going to check your two listed solutions to see if they can be more concise though. Thanks! You guys want to post an answer? – Pangamma Jan 02 '21 at 21:26

0 Answers0