我创建了一个带有可选属性 fixed
的对象。当我至少有一个 fixed
属性时,该代码有效。只有当我在整个 cols 数组中保留所有 fixed
未定义的 fixed
属性时,它才不起作用。导致错误的代码如下。
export interface configType {
width: number,
height: number,
minCellWidth?: number,
maxCellWidth?: number,
cols?: columnPropertyType[]
};
interface columnPropertyType {
index: number,
drag?: boolean,
minWidth?: number,
maxWidth?: number,
fixed?: string
};
export var config = {
height: 500,
width: 1200,
minCellWidth: 150,
maxCellWidth: 700,
cols: [
{
index: 0,
drag: true,
minWidth: 100,
maxWidth: 220
},
{
index: 2,
drag: true,
minWidth: 250
},
{
index: 5,
minWidth: 200,
maxWidth: 400
},
{
index: 10,
drag: false,
maxWidth: 300
}
]
};
只有在fixed 存在时,我才尝试获取fixed 的值,但是typescript 不允许我这样做。它向我显示错误消息 属性“固定”不存在于类型 {...}
for( var i=0; i<config.cols.length; i++ )
{
if( 'fixed' in config.cols[i] && config.cols[i].fixed.toLowerCase() === side.toLowerCase() )
{
return config.cols[i].index;
}
}
答案 0 :(得分:1)
在您当前的代码中,未键入 config
变量。
=> 尝试指定 config
变量的类型:
export const config: configType = {...}