【问题标题】:Typescript Error. Accessing a optional property from an object causing error打字稿错误。从导致错误的对象访问可选属性
【发布时间】:2023-03-17 22:44:01
【问题描述】:

我创建了一个带有可选属性fixed 的对象。当我至少有一个 fixed 属性时,该代码有效。仅当我将所有 fixed 未定义且在整个 cols 数组中没有 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;
    }
}

【问题讨论】:

    标签: typescript


    【解决方案1】:

    在您当前的代码中,未键入 config 变量。 => 尝试指定你config变量的类型:

    export const config: configType = {...}
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-07-26
      • 2022-12-17
      • 1970-01-01
      • 1970-01-01
      • 2021-05-03
      • 2020-11-07
      • 1970-01-01
      相关资源
      最近更新 更多