'Argument of type <Interface> is not assignable to parameter of type 'never'

I just started out doing some typescripts in angular and came across a problem that I wish for some assistance of.

list = [];
interface a {
   s : string;
   n : number;
}

const b = {'asdf',1234} as a;
list.push(b)

But I keep receiving the error

Argument of type a is not assignable to parameter of type 'never'.

Any suggestions on what I can do?



Solution 1:[1]

When you define in a class an array member like:

list = [];

List is going to be assigned by default the type never[], what you need here is to assign a proper type for the array, something like:

list: a[] = []; 

or

list: any[] = []; // If you don't care (not as good)

Probably you are defining in Angular your component like:

interface a {
   s : string;
   n : number;
}

class MyComponentFails {
  list = [];

  addToList() {
    const b = { s: 'asdf', n: 1234} as a;

    this.list.push(b) // Argument of type 'a' is not assignable to parameter of type 'never'.
  }
}

Which won't work, instead define it like this:

class MyComponentWorks {
  list: a[] = [];

  addToList() {
    const b = { s: 'asdf', n: 1234} as a;

    this.list.push(b) // Ok
  }
}

Playground

Solution 2:[2]

You have to specify the property name as below:

const b = { s: 'asdf', n: 1234 } as a;

Sample Typescript Playground

Solution 3:[3]

You forgot to add the key names. Interfaces and objects do not rely on the position of the arguments:

const list = [];

interface A {
    s: string;
    n: number;
}

const b: A = {s: 'asdf', n: 1234};
list.push(b)

I've added missing const for the list declaration. Keep in mind that it is a good practice to name types starting with capital letters. This way you can easier distinguish between variables and types/interfaces. There is also an alternative syntax with type A declared near the const b.

Solution 4:[4]

Take a look at Object Initializer for ways to initialize an object.

Also note, { 'asdf',1234 } isn't a valid object initialization syntax either. Of many ways, there is a short-hand notation for specifying objects that way(ES2015 onwards), but then the short-hand notation requires these to be valid variable identifiers and the key of the object and the name of the variable should be same.

Instead, we could have written...

const list = [];
interface A {
    s: string;
    n: number;
}

const s = 'asdf';
const n = 1234;

const b: A = { n, s }; //<-- Short-hand property initializer
list.push(b)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Daniel Rodríguez Meza
Solution 2 Yong Shun
Solution 3 MTP
Solution 4 Nalin Ranjan