1

I understand that TypeScript does not exist in runtime. But this should not be necessary in order to achieve my goal.

As an example, let's use the Omit<T> TypeScript utility type:

type MyType = {
  firstKey: string,
  secondKey: string,
  thirdKey: string
}

const x: Omit<MyType, 'secondKey' | 'thirdKey'> = {
  firstKey: 'value'
}

This makes me think that it could be possible to write a function that performs this "Omit" operation on existing objects, inferring the correct result type.

const removeKeys = <T extends Record<string, unknown>>(
  data: T,
  fields: Array<keyof T>
): Omit<T, typeof fields[number]> {
  // implementation doesn't matter right now
}

The idea is that the function could be used in this way:

const completeObject : MyType = {
  firstKey: 'value1',
  secondKey: 'value2',
  thirdKey: 'value3'
}

const ommitedObject = removeKeys(completeObject, ['secondKey', 'thirdKey'])
// TS could infer the `ommitedType` as Omit<MyType, 'secondKey' | 'thirdKey'>

But the signature I just wrote won't work, because typeof fields[number] is basically every key from MyType since typeof fields[number] is interpreted as typeof keyof T.

Is there a way to pass the ommitedKey argument in Omit<T, ommitedKey> dynamically? Not only the Omit<T, K>, which could be achieved using the other type Exclude<T, U> utility, but any other generic, such as Pick<T, K> or a custom generic type.

kelsny
  • 23,009
  • 3
  • 19
  • 48
ftoyoshima
  • 363
  • 5
  • 10
  • @vr partially. I'd expect some way to pass dynamically to any generics, but I see that my question is not very clear. I'll edit the question to make it clearer. – ftoyoshima Mar 22 '23 at 19:15
  • Dynamic how... all the answers shown essentially achieve the same functionality you are asking for. The only difference is that it is using rest parameters, while you want an array, and in that case, the only thing you need to do is remove `...`. – kelsny Mar 22 '23 at 19:17
  • 2
    It makes no difference. If I were to fix up your code and then implement a similar function for `Pick`, I get [this](https://tsplay.dev/WG2KVm). And now it's clearly the same as the answers posted in the question I linked... – kelsny Mar 22 '23 at 19:27

0 Answers0