项目

tiptap 使用 TypeScript

引言

Tiptap 的整个代码库都是用 TypeScript 编写的。如果你对它不熟悉或从未使用过,没关系,你不需要。

TypeScript 是通过添加类型(这就是名字的由来)来扩展 JavaScript。它引入了 JavaScript 中不存在的新语法。在浏览器运行前,这些新特性会被移除,但编译过程很重要,能帮助我们在早期发现错误。它会检查你是否正确地向函数传递了数据类型。对于大型和复杂的项目,这非常有价值。这意味着在发布代码给你之前,我们可以捕获很多问题。

总之,如果你的项目不使用 TypeScript,也没问题。 你仍然可以使用 Tiptap,并且大多数编辑器会为你提供不错的 Tiptap API 自动完成功能。

如果你的项目使用 TypeScript 并想扩展 Tiptap,有两类类型需要了解。

类型

选项类型

要扩展或为扩展创建默认选项,你需要定义一个自定义类型,如下所示:

import { Extension } from "@tiptap/core";

interface CustomExtensionOptions {
  awesomeness: number;
}

const CustomExtension = Extension.create<CustomExtensionOptions>({
  addOptions() {
    return {
      awesomeness: 100,
    };
  },
});

存储类型

为了为你的扩展存储添加类型,你需要将它作为第二个类型参数传递。

import { Extension } from "@tiptap/core";

interface CustomExtensionStorage {
  awesomeness: number;
}

const CustomExtension = Extension.create<{}, CustomExtensionStorage>({
  name: "customExtension",

  addStorage() {
    return {
      awesomeness: 100,
    };
  },
});

在扩展外部使用存储时,你必须手动设置类型。

import { CustomExtensionStorage } from "./custom-extension";

const customStorage = editor.storage.customExtension as CustomExtensionStorage;

命令类型

核心包还导出了一个 Command 类型,你需要将其添加到代码中定义的所有命令上。这是一个例子:

import { Extension } from "@tiptap/core";

declare module "@tiptap/core" {
  interface Commands<ReturnType> {
    customExtension: {
      /**
       * 自动完成中会包含此类注释。
       */
      yourCommand: (someProp: any) => ReturnType;
    };
  }
}

const CustomExtension = Extension.create({
  addCommands() {
    return {
      yourCommand:
        (someProp) =>
        ({ commands }) => {
          // …
        },
    };
  },
});

基本上就是这样了。我们会在背后自动处理其余部分。

在本文档中