Home > database >  Narrow object keys based on function parameter value
Narrow object keys based on function parameter value

Time:05-04

Is it with the newest version of typescript possible to narrow the properties of an object based on values supplied via parameters without specifying them as separate generic type for the function?

I would like the following to work in which the function signature of bar returns an object with the keys supplied as parameter. Theoretically if the parameters are constant it should be possible to infer the signature.

interface ModelType {
  id: string;
  name: string;
  timestamp: Date;
}


class Foo<T, K extends keyof T  = keyof T>{
  public bar(selectedField : K[]) : Pick<T,K>{
    return {} as any;
  }
}

const foobar = new Foo<ModelType>().bar(['id','name']);

console.log(foobar.id)          //Success
console.log(foobar.name)        //Success
console.log(foobar.timestamp)   //Should be an error

I tried any kind of combination with typeof selectedValues unarray but just end up with the full set of K.

CodePudding user response:

Class method generic types

You can add generic types to the class method to extends the generic type of the class as follow:

class Foo<T, K extends keyof T = keyof T>{
  // using generic types in your class method
  public bar<L extends K>(selectedField : L[]) : Pick<T,L>{
    return {} as any;
  }
}

TypeScript Playground

  • Related