Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

React's useContext can be used with Typescript's Record type in the following way:

  1. Define the Record type with a generic type parameter for the key and value types:
type MyRecord<K extends string | number | symbol, V> = Record<K, V>;
  1. Define the context interface with the Record type as its generic type parameter:
interface MyContext {
  data: MyRecord<string, string>;
}
  1. Create the context using the createContext function:
const MyContext = createContext<MyContext>({
  data: {}
});
  1. Use the useContext hook to access the context data:
const { data } = useContext(MyContext);
  1. Use the data object as a regular Record in Typescript:
const value = data["key"]; // value has type string