Codemirror on Angular for SQL hints works but gives Typescript typing error

Codemirror on Angular for SQL hints works but gives Typescript typing error

附加 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'

已找到解决错误的解决方法。

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

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'));
}