b00r00x0
b00r00x0

Reputation: 953

Typescript Error: Type {...} is not assignable to type 'User[]'

I started playing with Angular 4 and Typescript. I am totally new to Typescript. I saw this question got asked here, but I was not able to extract the answer to my problem.

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

export class UserComponent implements OnInit {
    me: User[];

    ngOnInit() {
       this.me = {
           name: 'Jochen',
           age: 31,
           email: '[email protected]',
           address: {
               street: 'Berlinerstraße 24',
               city: 'Berlin',
               state: 'Berlin'
           }
       };
    }
}

interface Address {
    city: string;
    street: string;
    state: string;
}

interface User {
    age: number;
    name: string;
    email: string;
    address: Address;
}

Here is the error I got when running ng serve:

ERROR in src/app/user/user.component.ts(11,7): error TS2322: Type '{ name: string; age: number; email: string; address: { street: string; city: string; state: strin...' is not assignable to type 'User[]'.
  Object literal may only specify known properties, and 'name' does not exist in type 'User[]'.

I wonder how to unserstand the second sentence, where it says 'name' does not exist in type 'User[]' it exists. Can one help me to understand what I am getting wrong?

Upvotes: 0

Views: 3353

Answers (1)

bugs
bugs

Reputation: 15313

me: User[] declares the variable me as an array of User elements, which I suspect is not what you want to do.

The correct syntax should simply be me: User

Upvotes: 4

Related Questions