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]>
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With