bloo
bloo

Reputation: 1560

Defining a type whose key and value are the key of a given filter and its type

I am trying to write a function that takes a specific filter key whose value is a keyof an interface that I have defined. I would like the returned result to be an object that has the filter value present as one of the keys and the type of that key in the interface to be the corresponding value.

I have tried juggling through combinations of typings, but I fear I do not understand typescript well enough to figure this out. Here is my implementation,

Interface

interface MyModel {
  a: string;
  b: number;
  c: boolean;
}

Function

function myfunction(filter: keyof MyModel): {
  date: Date;
  [key: data.filter]: typeof filter
} {
  // ...
}

The above function is wrong, but I hope gives off the idea of what I am trying to get at. My workaround currently is to use Partial<MyModel> which works but requires null checking the value, this is illustrated below.

function myfunction(filter: keyof MyModel): Partial<MyModel> & {
  date: Date;
} {
  // ...
}

My question is, is there a way to narrow the typings in the way illustrated above?

Upvotes: 0

Views: 24

Answers (1)

Oleksandr Kovalenko
Oleksandr Kovalenko

Reputation: 616

interface MyModel {
  a: string;
  b: number;
  c: boolean;
}

function myFunction<TKey extends keyof MyModel>(filter: TKey): Pick<MyModel, TKey> & { date: Date } {
  throw new Error("Not implemented")
}

// examples of return values types:
// myFunction('a') // { a: string, date: Date }
// myFunction('b') // { b: number, date: Date }
// myFunction('c') // { c: boolean, date: Date }

Upvotes: 1

Related Questions