how to create d.ts type definition of existing Context module?

16 Views Asked by At

I have a hybrid project that uses js and tsx/ts files.

File 1 is called form.js and I am exporting a context module:

const FormContext = React.createContext({})
....

When I try to access the values/functions from FormContext in a tsx file, IntelliSense complains because there's no typed definition for FormContext. Example:

const formContext = React.useContext(FormContext)

formContext.registerControl({value: 'lala', default: 'blabla')

// I get this complain: Property 'register' does not exist on type '{}'

these are the props that were supposed to be there:

type FormContextProps = {
  register: (param: { fieldName: string; defaultValue: any; required?: boolean }) => void,
  onChange: (fieldName: string, value: any) => void,
};

I am aware that I can define React.useContext(FormContext) as FormContextProps on my tsx file, but I don't want to be doing that everytime I use the FormContext in different files.

How can I declare that in a d.ts file so it's available everywhere?

So far I got:

type FormContextProps = {
  register: (param: { fieldName: string; defaultValue: any; required?: boolean }) => void,
  onChange: (fieldName: string, value: any) => void,
};

declare global {
  type FormContext = typeof React.createContext<FormContextProps>({});
}

export {}

but that doesn't work. Can I get some help please?

1

There are 1 best solutions below

0
Vania Oliveira On

I was able to make it work.

On the same folder where I have form.js I created a declaration file form.d.ts and added the following there:

declare module './form' {
  type FormContextProps = {
    register: (param: { fieldName: string; defaultValue: any; required?: boolean }) => void;
    onChange: (fieldName: string, value: any) => void;
  };

  export const FormContext: Context<FormContextProps>;
}

IntelliSense is picking it up now.