Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why is my Typescript strong typing not working?

I have the following model:

export class ProductModel {    
    _id: string = '';
    brand: string = '';
    description: string = '';
    images: string[] = [];
    price: number = 0;
    discount: number = 0;
    rating: number = 0;
    category: string = '';
    attributes: {} = {};
    specifications: string[] = [];
    productCount:number = 0;
}

My ngrx reducer uses the above model:

const initialState = {
    products: ProductModel[] = [], 
    productCount: 0
}

// const initialState = new ProductModel();

export const ProductReducer = createReducer(
    initialState,

    on(StoreProducts, (state, action) => {
        console.log('ProductReducer.StoreProducts.products', action.productData)
      return {
        ...state,
        products: action.productData.products,
        productCount: action.productData.productCount,        
      };
    }),
)

I get the following error about this declaration products: ProductModel[] = [], in the initialState. The error says:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Element implicitly has an ‘any’ type because expression of type ‘any’ can’t be used to index type ‘typeof ProductModel’.ts(7053)
An element access expression should take an argument.ts(1011)

>Solution :

Your syntax of the object literal is wrong, you’re trying to assign a type [] to ProductModel[] as the default value or something like that and not providing a proper object literal.

Use some proper form like:

const initialState: {products: ProductModel[], productCount: number} = {
  products: [], 
  productCount: 0
} 

const initialState2 = {
  products: [] as ProductModel[], 
  productCount: 0
} 

const initialState3 = new class {
  products: ProductModel[] = [];
  productCount = 0
} 

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading