Error: Type '[number] | [number, number, number, number]' is not assignable to type '[number]'

Viewed 9655

After the update from the angular 5.1 to 6.1 I stared to receive some error from my code like the following:

Error: ngc compilation failed: components/forms/utils.ts(5,3): error TS2322: Type '[number] | [number, number, number, number]' is not assignable to type '[number]'.

Follows the code:

export function bsColumnClass(sizes: [number]) {

  let sizebs = ['col-xs-', 'col-sm-', 'col-md-', 'col-lg-',];

  sizes = sizes || [12, 12, 12, 12];

  let className = sizes.map(function callback(value, index, array) {
    return sizebs[index].concat(value.toString());
  }).join(" ");

  return className;
}

I notice that the problem is because I have a function parameter sizes: [number] and after that I'm traing to do this line of code: sizes = sizes || [12, 12, 12, 12];

Can you tell me the better way to solve this?

3 Answers

In Typescript, arrays are declared in the following way

type[]

instead of

[type]

if you try to write your code with theses changes, it should work, however, correct me if I'm wrong, but, are you trying to assign a list of number to sizes in case sizes is undefined ?

If so, you should type your function accordingly

function bsColumnClass(sizes?: number[]) {
}

The ? will ensure that event if you don't provide a variable to the function, the code stays statically typed and accept a variable argument

If you want to define an array of numbers the syntax is number[] (and in general for arrays we have type[]). What you defined there is a tuple type, which has a fixed number of elements and can have heterogeneous element types.

export function bsColumnClass(sizes: number[]) {


}

Or if you want to mandate the caller pass exactly 4 elements in the array, which appears to make sense in this case as sizebs is fixed, you can use the tuple type:

export function bsColumnClass(sizes: [number, number, number, number]) {

  let sizebs = ['col-xs-', 'col-sm-', 'col-md-', 'col-lg-',];

  sizes = sizes || [12, 12, 12, 12];

  let className = sizes.map(function callback(value, index, array) {
    return sizebs[index].concat(value.toString());
  }).join(" ");

  return className;
}

In question I found syntax problem in argument sizes: [number] instead of that you can use sizes: number[].

You can try this:

export function bsColumnClass(sizes: number[]) {
  const sizebs = ['col-xs-', 'col-sm-', 'col-md-', 'col-lg-'];

  sizes = sizes || [12, 12, 12, 12];

  const className = sizes
    .map(function callback(value, index, array) {
      return sizebs[index].concat(value.toString());
    })
    .join(' ');

  return className;
}

//bsColumnClass([1, 2, 6, 3]);
Related