我有一个可以选择接收某些属性的数组。您如何使用循环访问它们中的每一个?我正在编写一个插件,它具有响应属性,可以动态适应不同的设备。埃斯林特向我发出了这个警告:
const exampleObj: responsiveProps 该元素隐式属于“any”类型,因为“string”类型的表达式不能用于索引“responsiveProps”类型。在类型参数“string”的“responsiveProps”类型中找不到索引签名
type responsiveProps = {
heightRow?: string,
widthColumn?: string,
countColumns?: number,
countRows?: number,
rowGap?: number
}
const exampleObj: responsiveProps = {
heightRow: "300px",
countRows: 3
}
for (const key in exampleObj) {
if (Object.prototype.hasOwnProperty.call(exampleObj, key)
&& exampleObj.hasOwnProperty(key)) {
// здесь exampleObj[key] будет выбивать вышеупомянутое предупреждение
const responsiveProp = exampleObj[key];
console.log(responsiveProp)
}
}
//получается сделать только так:
if(exampleObj.countColumns)
/* действие */
console.log(exampleObj.countColumns);
if(exampleObj.countRows)
/* действие */
console.log(exampleObj.countRows)
这是另一个尝试:
for (let i = 0; i < Object.keys(exampleObj).length; i++) {
const nameProperty: string = Object.keys(exampleObj)[i];
if(exampleObj.hasOwnProperty(nameProperty)) {
//да, здесь снова предупреждение
console.log(exampleObj[nameProperty]);
}
}
在我看来,成功的机会更大。尽管打字稿绝对不在乎礼貌,对谁以及看起来如何
问题的附录:
const exampleObj: responsiveProps = {
heightRow: "300px",
countRows: 3
}
const needfulResponsiveProps: responsiveProps = {};
for (const key of Object.keys(exampleObj) as (keyof responsiveProps)[]) {
//Тип "string | number | undefined" не может быть назначен для типа "undefined".
Тип "string" не может быть назначен для типа "undefined"
needfulResponsiveProps[key] = exampleObj[key]
}
1 个回答