Typescript
note
The core types will be the default of Slate in the near future, see this PR.
These are provided by Plate core in the meantime. See our full Typescript example here.
Plate is providing a typed layer on top of Slate, using mostly generic types.
Differences with Slate types:
Editor
type:TEditor<V>
whereV
represents the "value" being edited by Slate. In the most generic editor,V
would be equivalent toTElement[]
(since that is what is accepted as children of the editor). But in a custom editor, you might haveTEditor<Array<Paragraph | Quote>>
.- Other
TEditor
-and-TNode
-related methods have been also made generic, so for example if you usegetLeafNode(editor, path)
it knows that the return value is aTText
node. But more specifically, it knows that it is the text node of the type you've defined in your custom elements (with any marks you've defined).TEditor
type is not matching with SlateEditor
type, so Plate has forked (type-only) all Slate methods that useEditor
that you should use. - This replaces the declaration merging approach, and provides some benefits. One of the drawbacks to declaration merging was that it was impossible to know whether you were dealing with an "unknown" or "known" element, since the underlying type was changed. Similarly, having two editors on the page with different schemas wasn't possible to represent. Hopefully this approach with generics will be able to smoothly replace the declaration merging approach. (While being easy to migrate to, since you can pass those same custom element definitions into
TEditor
still.)
First, let's create a new file to define our MyValue
type, which will be the type of our editor.children
.
note
Naming convention:
My
is short and explicit.T...Element
is used because...Element
is already used by Plate UI components and we don't want naming conflicts between imports.T...
is also a way to differenciate Plate types with Slate types.
MyValue
is the most important type as most of the core types are derived from it.
The following types are optional but highly recommended, writing generic types are redundant so try doing it only once:
Finally, let's define typed functions:
Usage example: