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.