Attaching Stackblitz: https://stackblitz.com/edit/angular-ivy-vxm6gg?file=src/app/app.component.ts
I am trying to implement CodeMirror in Angular 10 for SQL hints as here: https://codemirror.net/mode/sql/. The functionality works correctly on the webpage, and I can also see the correct options in the console log. But, I also see this error not assignable to type 'ShowHintOptions'
because I am incorrectly setting the hintOptions
option. I haven't found any alternative examples, and my attempts to follow the correct typing were unsuccessful. Please help.
Installation
npm install codemirror @types/codemirror
Code
// 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
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'
Got a workaround to resolve the error.
Add a variable of any type to hold the values.
const options: any = {
tables: {
users: ["name", "score", "birthDate"],
countries: ["name", "population", "size"]
}
};
Cast the variable as ShowHintOptions
hintOptions: options as codemirror.ShowHintOptions,
New code
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'));
}