F
F
faleaksey2019-04-01 16:58:47
JavaScript
faleaksey, 2019-04-01 16:58:47

How to properly describe an object in a TypeScript model?

Hello! I just started learning TypeScript and when describing the types used in the model, an error occurs, namely "Object literal may only specify known properties, and 'value' does not exist in type '{ [key: number]: any; }'"...
how to correctly set the type of the _total object and its internal values?

export default class Model {

    _total: { [key: number]: any } = {};

    constructor() {
        super();
        this._total= {
            value: 1,
            btn: {
                add: true,
                rem: false
            }
        };
    }
}

Answer the question

In order to leave comments, you need to log in

2 answer(s)
V
Vladimir Proskurin, 2019-04-01
@faleaksey

Well, your _total key is not a number, it's a string
UPD: here it is described about the index signature https://basarat.gitbooks.io/typescript/docs/types/...

E
eRKa, 2019-04-01
@kttotto

export default class Model {
    _total: { [key: string]: any } = {};

    constructor() {
        super();
        this._total['value'] = 1;
        this._total['btn'] = {
                add: true,
                rem: false
        };
    }
}

If you turn everything into any, then there will be no sense from typescript. So it's better to type your properties like this
class Total {
    value: number,
    btn: {
        add: boolean,
        rem: boolean
    }
};

export default class Model {
    _total: Total;

    constructor() {
        super();
        this._total= new Total {
            value: 1,
            btn: {
                add: true,
                rem: false
            }
        };
    }
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question