Search code examples
typescripttypescript-generics

Generic interface property type based off of passed in type property


I have a generic interface that has a field that is based off of the passed in type.

I'm wondering if it's possible to then have another field be of any type of the passed in type

for example:

interface sampleObject {
   name: fullName
   age: number
   address: string
}

interface fullName{
   first: string
   middle: string
   last: string
}

// imagine I pass in type sampleObject

interface genericType<T, Key = keyof T> {
  field: Key // valid values are "name" | "age" | "address"
  fieldTypes: ??? // I want the valid types to be fullName | number | string
}

I've tried using fieldTypes: T[keyof T] and this almost gets me what I want but it says the type is fullName | number | string | undefined, which then throws error ts(2322).

I'm not sure if I'm approaching this the right way or not.


Solution

  • maybe something like this could be useful:

    type KVPairs<T, K extends keyof T = keyof T> = 
    K extends keyof T
        ? { field: K, fieldTypes: T[K] } 
        : never;
        
    type genericType<T> = KVPairs<T>;