Search code examples
typescripttypescript-types

How to make typescript treat two keyof as same type


I want to make a reducer to modify an appollo search variable.

type SearchReducer = Reducer<
  WhereInput,
  { key: keyof WhereInput; value: WhereInput[keyof WhereInput] }
>;

useReducer<SearchReducer>((prev,{key,value})=>{
    const newValue = {...prev};
    // compile failure here
    newValue[key] = value;
    return newValue;
})

It said that I can't assume newValue[key] share the same type with value, I think it is right but how can I restrict that two keyof in my type must be the same value?


Solution

  • To restrict key and value your SearchReducer type can be rewritten as follows:

    type SearchReducer<T extends keyof WhereInput> = Reducer<
      CaseWhereInput,
      { key: T; value: WhereInput[T] }
    >;
    

    It's hard to give you a complete solution though since I am not familiar with any of the types you are using or the appollo search you mention (CaseWhereInput, WhereInput, Reducer) or the signature useReducer function.