Home > front end >  Angular - How to resolve Type 'number' is not assignable to type 'never'
Angular - How to resolve Type 'number' is not assignable to type 'never'

Time:10-22

In Angular-14, I have this service:

import { Injectable } from '@angular/core';

@Injectable({
  providedIn: 'root'
})
export class PaginationService {

    //Pagination Variables

    temppage: number = 0;
    pageField = [];
    exactPageList: any;

    constructor() {
    }

    // On page load
    pageOnLoad() {
        if (this.temppage == 0) {

            this.pageField = [];
            for (var a = 0; a < this.exactPageList; a  ) {
                this.pageField[a] = this.temppage   1;
                this.temppage = this.temppage   1;
            }
        }
    }
}

But I got this error:

Type 'number' is not assignable to type 'never'

and this.pageField[a] is highlighted.

How do I get this resolved?

Thanks

CodePudding user response:

Change your declaration:

pageField = [];
TO
pageField: Number[] =[];

It will fix your compilation error.

CodePudding user response:

The issue is that the type of your filed pageField is never[].

You can check it when you hoover over NeverArray.pageField in this Stackblitz Example

class NeverArray {
    // the type id never[]
    pageField = [];
}

To fix the issue, you should explicitly add the type of the array:

class NumericArray {
    pageField: Array<number> = [];
    foo() {
      this.pageField[0] = 1;
    }
}

When you do not explicitly type or initialize an array, the rules are quite tricky: see https://stackoverflow.com/a/72660888/1041641

CodePudding user response:

If you have strictNullChecks: true enabled in your tsconfig.json, you need to explicitly type your variables which get passed empty array default values ([]) otherwise TypeScript will expect them to always remain as [] (the typescript way of saying this is never[])

In your case, pageField = [] sets the type of pageField to be never[]. By changing this to pageField: number[] = [] you are informing TypeScript that pageField expects to contain numbers, therefore when a number is passed into that array, there is no error

  • Related