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
...
}
在研究typescript时,出现字符串不能用作索引的错误。
为什么任何类型都可以用作索引,而字符串是不可能的?怎么了?和如何解决?谢谢你的帮助。
我试图用typescript处理DOM元素,但我面临一个问题。我真想知道出了什么事。
发生这种情况的原因是,在您的示例中,key
的第一个声明实际上不是字符串。key
的类型为showModal
。这是TypeScript的一个奇特之处。它看到您正在使用key
来索引HTMLDialogElement
,因此它将类型限制为仅用于索引HTMLDialogElement
的有效字符串。即,存在于这样一个对象上的属性名之一。
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
}