在 HTML 类型上找不到"字符串"索引的原因是什么?


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
}

最新更新