Siva Chandran
Siva Chandran

Reputation: 47

Typescript Error. Accessing a optional property from an object causing error

I've created an object with an optional property fixed. The code works when I have atleast one fixed property. It doesn't work only when I leave all fixed undefined that is no fixed property in the entire cols array. The Error causing code is below.

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
        }
    ]
};

I am trying to get the value of fixed only if fixed exists, but typescript is not allowing me to do this. It shows me a error message Property 'fixed' doesn't exist on type {...}

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;
    }
}

Upvotes: 1

Views: 100

Answers (1)

David ROSEY
David ROSEY

Reputation: 1805

In your current code, the config variable is not typed. => Try specifying the type of you config variable:

export const config: configType = {...}

Upvotes: 1

Related Questions