typescriptngrx

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:

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
    }