'Typescript parameter type depending on another parameter

I want to create generic function for setStore, the function is simple:

const setStore = <T>(store:T) => <K extends keyof T,U extends boolean>(property: K,data: U extends true? Partial<T[K]>:T[K],partialUpdate:U) => {
if (partialUpdate) {
      store[property] = { ...store[property], ...data }
    } else {
      store[property] = data // Error Type 'U extends true ? Partial<T[K]> : T[K]' is not assignable to type 'T[K]'.
    }
}

I want data's type to be T[K] or Partial<T[K]> depending on the partialUpdate parameter is true or false. But I get the error Type 'U extends true ? Partial<T[K]> : T[K]' is not assignable to type 'T[K]'. because somehow typescript can't decide whether the data type is T[K] or Partial<T[K]>



Solution 1:[1]

Just tell typescript that data really is a T[K].

const setStore = <T>(store:T) => <K extends keyof T,U extends boolean>(property: K,data: U extends true? Partial<T[K]>:T[K],partialUpdate:U) => {
  if (partialUpdate) {
        store[property] = { ...store[property], ...data }
  } else {
        store[property] = data as T[K]
  }
}

Playground link

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 BorisTB