Alex
Alex

Reputation: 690

How do I access the "Editor" type defined by TinyMCE in React and TypeScript?

I am trying to figure out how to access types defined in an NPM module.

TinyMCE has an editor React component called Editor and it contains an onInit method that takes two parameters, an event and the editor itself, also an Editor type but different from the component.

So I import the Editor component from the library by doing

import { Editor as TinyMCEEditor } from '@tinymce/tinymce-react';

And I define the editor as the following...

<TinyMCEEditor
   apiKey="asdf"
   onInit={(evt, editor) => onInitCallBack(evt, editor)}
   ...
/>

Then I tried to define the callback to match the expected type

const onInitCallBack = (_, editor: Editor) => {
   ...
};

The strange thing is it is able to recognize the Editor type when it is moused over is given as.

(parameter) editor: Editor

As well as the event's type:

(parameter) evt: {
    readonly type: string;
    readonly target: any;
    readonly isDefaultPrevented: () => boolean;
    readonly preventDefault: () => void;
    ...etc
}

But on the onInitCallBack when I try to define the Editor type, it says it cannot find the name 'Editor':

type Editor = /*unresolved*/ any
Cannot find name 'Editor'. ts(2304)

What do I need to do to make it see the Editor type that is defined in the NPM package?

If I try to use TinyMCEEditor as a type I get the following error.

(parameter) editor: Editor
Argument of type ‘import("e:/Git/web-app-release-notes-editor/node_modules/tinymce/tinymce").Editor’ is not assignable to
parameter of type ‘import("e:/Git/web-app-release-notes-editor/node_modules/@tinymce/tinymce-
react/1lib/cjs/main/ts/components/Editor").Editor’

Type ‘Editor’ is missing the following properties from type ‘Editor’: elementRef, boundHandlers, rollbackTimer, valueCursor, and
23 more. t5(2345)

Upvotes: 7

Views: 2851

Answers (1)

Fraser
Fraser

Reputation: 17094

You are confusing the React component Editor and the tinymce Editor - notice they have the same name. Surly you need something like...

import { Editor } from '@tinymce/tinymce-react';
import { Editor as TinyMCEEditor } from 'tinymce';

Then

const editorRef = useRef<TinyMCEEditor | null>(null);

and...

<Editor
   onInit={(evt, editor) => editorRef.current = editor}
   ...
/>

Although I might have screwed the syntax up here...

Upvotes: 15

Related Questions