首页 > 解决方案 > Angular 上的 Codemirror for SQL 提示有效,但出现 Typescript 输入错误

问题描述

附加 Stackblitz:https ://stackblitz.com/edit/angular-ivy-vxm6gg?file=src/app/app.component.ts

我正在尝试在 Angular 10 中为 SQL 提示实现 CodeMirror,如下所示:https ://codemirror.net/mode/sql/ 。该功能在网页上正常运行,我还可以在控制台日志中看到正确的选项。但是,我也看到了这个错误not assignable to type 'ShowHintOptions',因为我错误地设置了hintOptions选项。我还没有找到任何替代示例,并且我尝试按照正确的输入进行操作没有成功。请帮忙。

安装 npm install codemirror @types/codemirror

代码

// imports
import * as codemirror from 'codemirror';
import 'codemirror/mode/sql/sql';
import 'codemirror/addon/hint/show-hint';
import 'codemirror/addon/hint/sql-hint';

// Element Ref for this HTML <textarea #ref></textarea>
@ViewChild('ref', { static: true }) ref: ElementRef; 
editor: CodeMirror.EditorFromTextArea;

ngOnInit(): void {
  this.editor = codemirror.fromTextArea(this.ref.nativeElement, {
    mode: 'text/x-mysql',
    showHint: true,
    extraKeys: { 'Ctrl-Space': 'autocomplete' },
    hintOptions: {
      tables: {
        'users': ['name', 'score', 'birthDate'],
        'countries': ['name', 'population', 'size']
      }
    }
  });
  console.log(this.editor.getOption('hintOptions'));
}

错误

 error TS2322: Type '{ tables: { users: string[]; countries: string[]; }; }' is not assignable to type 'ShowHintOptions'.
      Object literal may only specify known properties, and 'tables' does not exist in type 'ShowHintOptions'.
    
    42           tables: {
                 ~~~~~~~~~
    43             'users': ['name', 'score', 'birthDate'],
       ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    44             'countries': ['name', 'population', 'size']
       ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    45           }
       ~~~~~~~~~~~
    
      node_modules/@types/codemirror/addon/hint/show-hint.d.ts:81:9
        81         hintOptions?: ShowHintOptions;
                   ~~~~~~~~~~~
        The expected type comes from property 'hintOptions' which is declared here on type 'EditorConfiguration'

标签: sqlangulartypescripttypescript-typingscodemirror

解决方案


有一个解决方法来解决错误。

添加任何类型的变量来保存值。

const options: any = {
  tables: {
    users: ["name", "score", "birthDate"],
    countries: ["name", "population", "size"]
  }
};

将变量转换为ShowHintOptions

hintOptions: options as codemirror.ShowHintOptions,

新代码

ngOnInit(): void {
 const options: any = {
  tables: {
    users: ["name", "score", "birthDate"],
    countries: ["name", "population", "size"]
  }
};
this.editor = codemirror.fromTextArea(this.ref.nativeElement, {
  mode: "text/x-mysql",
  hintOptions: options as codemirror.ShowHintOptions,
  extraKeys: { "Ctrl-Space": "autocomplete" }
});
console.log(this.editor.getOption('hintOptions'));
}

推荐阅读