I want to have typescript assert that a 'new' string is not part of a union, an existing set the string will be added to.
I'm looking for an independent, standalone line of code, but that's just a nice-to-have.
So, the simple, albeit contrived situation:
type FruitOptions = 'banana' | 'apple' | 'grape'
type NewFruitOption = 'pear'
// ^ being passed into a function ^
// Assert: FruitOptions does not contain NewFruitOption
I don't think sharing this is necessary, but this is the utility function I'm seeking to employ this technique on:
// These are inferred generics (since they come after the = sign), do not pass them in.
export const renameKey = <
OldKey extends keyof T,
NewKey extends string, // should NOT already be keyof T
T extends Record<string, unknown>
>(
oldKey: OldKey,
newKey: NewKey,
userObject: T
): Record<NewKey, T[OldKey]> & Omit<T, OldKey> => {
const { [oldKey]: value, ...common } = userObject
return {
...common,
...({ [newKey]: value } as Record<NewKey, T[OldKey]>)
}
}
