I need to have an input variable be determined by a second boolean
variable as directive to be used later on.
type TypeWithAge = {
name: string,
age: number
}
type TypeWithoutAge = MakeOptional<TypeWithAge, "age">;
type TypeWithAgeConditional<withName> = withName extends true ? TypeWithoutAge : TypeWithAge;
Now I need to have the function change the input param based on withName
.
async function upsertFunction<withName extends boolean>(
upsertItem: TypeWithAgeConditional<withName>,
includeName: withName
): boolean {
if (includeName){
upsertItem = { ...upsertItem, name: 'someValue' }
}
await writeItemToDb(upsertItem) // TS error since input of writeItemToDb expects TypeWithAge and cannot be changed in my case
return true
}
The only workaround I have thus far is using
await writeItemToDb(upsertItem as TypeWithAge)
Logically it makes sense since the upsertItem
will always correctly be of type TypeWithAge
but using as xxx
feels like a hardcoded pitfall waiting to happen.
How do I get upsertItem
to also be of type TypeWithAgeConditional
and get writeItemToDb
to understand it will always be of correct type TypeWithAge
?
There are other questions that use this to determine the output of a function but I have solved that in my code already and still can’t get this to work.