const dialog = document.getElementById("input-dialog") as HTMLDialogElement;
const someFunction = () => {
const key = "showModal";
dialog[key]();
//No error occurred
const key: string = "showModal"
dialog[key]()
// Error No index signature with a parameter of type 'string' was found on types
...
}
While studying typescript, an error occurred that the string could not be used as an index.
Why can any type be used as an index and string is not possible?
What is wrong? and How to fix it? I'd appreciate your help.
I tried to handle the DOM element with typescript but I face a problem. I really want to know What is wrong.
CodePudding user response:
The reason this is happening is that in your example, the first declaration of key
isn't actually a string. The type of key
is showModal
. This is a TypeScript oddity. It sees that you're using key
to index an HTMLDialogElement
so it constrains the type to only valid strings for indexing an HTMLDialogElement
. I.e, one of the names of the properties that exist on such an object.
const dialog = document.getElementById("input-dialog") as HTMLDialogElement;
const foo = () => {
const key = "showModal";
// type of key is "showModal"
dialog[key](); // works
}
const bar = () => {
const key: string = "showModal";
// type of key is string
dialog[key]; // doesn't work
}
const foz = (key: string) => {
// type of key is string
dialog[key]; // doesn't work
}
const baz = (key: "showModal" | "show") => {
dialog[key]; // works
}
CodePudding user response:
The key variable is being re-declared with a type of string after it has already been initialized with a value. This causes a TypeScript error because the type of key has already been inferred as a string based on its initial value.
To fix this try following code:
const dialog = document.getElementById("input-dialog") as HTMLDialogElement;
const someFunction = () => {
let key: string = "showModal";
dialog[key]();
//No error occurred
key = "showModal"
dialog[key]()
// No error
}