[Vuejs]-Typescript : how to define type for object property?

3πŸ‘

βœ…

Normally, you do it by defining a type (like your IProduct) for the object as a whole, and assigning that type to the variable referring to the object (form) when you declare it. For instance:

interface FormType {
    date: Array<something>;
    R20s: Array<something>;
    type: number;
    cats: null | something;
    selected_product: Array<IProduct>;
}
// ...
const form: FormType = {
//        ^^^^^^^^^^βˆ’βˆ’βˆ’βˆ’βˆ’βˆ’βˆ’βˆ’βˆ’βˆ’βˆ’βˆ’βˆ’βˆ’βˆ’βˆ’βˆ’βˆ’βˆ’βˆ’βˆ’βˆ’βˆ’βˆ’βˆ’βˆ’βˆ’βˆ’βˆ’βˆ’βˆ’βˆ’βˆ’βˆ’βˆ’ giving type to object
    date: [],
    R2Os: [],
    type: 1,
    cats: null,
    selected_product: [],
    //                ^^βˆ’βˆ’βˆ’βˆ’βˆ’βˆ’βˆ’βˆ’βˆ’βˆ’βˆ’βˆ’βˆ’βˆ’βˆ’βˆ’βˆ’βˆ’βˆ’βˆ’βˆ’βˆ’βˆ’βˆ’βˆ’ value
};

but you can also do it with an inline type assertion:

const form = {
    date: [],
    R2Os: [],
    type: 1,
    cats: null,
    //                vvβˆ’βˆ’βˆ’βˆ’βˆ’βˆ’βˆ’βˆ’βˆ’βˆ’βˆ’βˆ’βˆ’βˆ’βˆ’βˆ’βˆ’βˆ’βˆ’βˆ’βˆ’βˆ’βˆ’βˆ’βˆ’ value
    selected_product: [] as Array<IProduct>,
    //                  ^^^^^^^^^^^^^^^^^^^βˆ’βˆ’βˆ’βˆ’βˆ’βˆ’ type assertion
};

The TypeScript handbook is worth reading from beginning to end. It covers all of the basics in a very concise way.

πŸ‘€T.J. Crowder

Leave a comment