javascript - 在 for 循环中使用对象属性时出错(TypeScript)
问题描述
我有一个简单的函数,在这个函数内部它循环一个对象并尝试使用对象属性值,但它得到一个错误。为什么我不能使用对象属性值style[key]
let createFunction = function (
elmName: string,
style: object = {
height: '100px',
width: '100px',
border: '1px solid red'
}
): void {
let
newELM = document.createElement(elmName);
let customStyle : any = '';
//set the style to custom style
for (let key in style ){
if (style.hasOwnProperty(key)){
customStyle += key + ':' + style[key] + ';'; //___________ERROR on style[key]
}
}
newELM.setAttribute('style', customStyle);
if (window){
document.body.appendChild(newELM);
}
}
createFunction('div');
错误:
Element implicitly has an 'any' type because expression of type 'string' can't be used to index type '{}'.
No index signature with a parameter of type 'string' was found on type '{}'.ts(7053)`
解决方案
这是因为您的style
参数具有通用对象类型。您可以更具体地解决此问题
style: { [index: string]: string } = {
height: "100px",
width: "100px",
border: "1px solid red",
}
推荐阅读
- flutter - 在考虑图像大小和容器大小的情况下将一些图像定位在容器内
- mongodb - Apache Zeppelin 中的 org/bson/conversions/Bson 错误
- javascript -
nextjs 中的组件替代 - laravel - Flutter + Laravel:无法在服务器上注册新用户
- python - 以太网数据树莓派
- javascript - Converting from epoch date in javascript
- php - Parse error: syntax error, unexpected ‘?’. But
- google-calendar-api - Google calendar id length and event id length
- reactjs - 模拟异步函数开玩笑以测试传递状态
- python - Python Tkinter Restart the program without killing it