You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何为模型声明预期导出类型?Monaco Editor TS校验问题

问题排查与解决步骤

1. 修复类型定义语法错误

你的类型声明存在语法问题,TypeScript的对象类型定义必须添加=:

// 错误写法
type MyType {okok:string}

// 正确写法
type MyType = {okok: string};

2. 配置TypeScript编译选项并确保声明文件被识别

创建声明模型前,先配置Monaco的TypeScript编译选项,开启严格校验模式,同时确保声明模型能被语言服务检测到:

// 配置TS编译参数
monaco.languages.typescript.typescriptDefaults.setCompilerOptions({
  strict: true,
  module: monaco.languages.typescript.ModuleKind.ESNext,
  target: monaco.languages.typescript.ScriptTarget.ESNext,
  allowSyntheticDefaultImports: true
});

// 创建声明模型
monaco.editor.createModel(
  `
type MyType = { okok: string };
declare module './component.tsx' {
  export default MyType;
}
`,
  "typescript",
  monaco.Uri.parse("file:///component.d.tsx")
);

3. 确保路径匹配准确

编辑器的path设为component.tsx,声明模块的./component.tsx要和编辑器文件的路径保持相对关系一致。如果路径关联有问题,可尝试改用绝对路径声明:

declare module 'file:///component.tsx' {
  export default MyType;
}

4. 强制触发语言服务重新校验

若创建模型后未自动触发校验,可手动刷新TypeScript语言服务:

monaco.languages.typescript.typescriptDefaults.getLanguageService().refresh();

测试验证

在component.tsx中编写不符合类型的代码,比如:

const comp = { notOk: 'test' }; // 此处应触发类型不匹配错误
export default comp;

配置正确的话,Monaco编辑器会立即显示类型校验错误提示。

内容的提问来源于stack exchange,提问作者localhost

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.09 23:25:25