Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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]>

like image 228
Xin Jin Avatar asked Apr 16 '26 09:04

Xin Jin


1 Answers

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

like image 73
BorisTB Avatar answered Apr 22 '26 23:04

BorisTB



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!