3

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

1 Answer 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

Sign up to request clarification or add additional context in comments.

1 Comment

Ah, ok, thanks :) it sounds like a solution. But I just try to avoid to use type assertion, because maybe it's not properly typed. And i don't know why Typescript can't figure out the proper type in this case

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.