2

in my angular application I want to use an array of object of id and role in below manner

let userRole: Array<...> = [
                       { id: 1, name: 'Admin' },
                       { id: 2, name: 'Super Admin' },
                       { id: 2, name: 'User' },
                       { id: 2, name: 'Watcher' }
                    ];

BUT I am confused what need to fill up in place of ... ?

Array < Object > or Array <Any>

Trial 1 :

var role = { id: number; name: string; };

and then Array <role> but it gives error

Trial 2 : adding with different class file

role.ts

export class Role {
    constructor(
        public id: number,
        public name: string
    ) { }
}

and add in my file as

import { Role }      from './role';

export class HeroFormComponent {

   let userRole: Array<Role> = [
                       { id: 1, name: 'Admin' },
                       { id: 2, name: 'Super Admin' },
                       { id: 2, name: 'User' },
                       { id: 2, name: 'Wacher' }
                    ];

But gives error

Error: SyntaxError: Unexpected strict mode reserved word

1 Answer 1

7

Your first and best option is to simply not have a type annotation:

let userRole = [
                       { id: 1, name: 'Admin' },
                       { id: 2, name: 'Super Admin' },
                       { id: 2, name: 'User' },
                       { id: 2, name: 'Watcher' }
                    ];

The inferred type of userRole will be Array<{ id: number, name: string }>.

If you really want a type annotation for whatever reason, you can write either

let userRole: { id: number, name: string }[] = [ ...

or

let userRole: Array<{ id: number, name: string }> = [ ...

These two syntaxes are identical in behavior.

If you're going to be using this type a lot, you might want to make an interface for it so you can re-use the name in other places:

interface Role {
  id: number;
  name: string;
}

Now you can write

let userRole: Role[] = [ ...

When you declare an initialized field in a class, you do not use var or let:

export class HeroFormComponent {

   userRole = [
                       { id: 1, name: 'Admin' },
                       { id: 2, name: 'Super Admin' },
                       { id: 2, name: 'User' },
                       { id: 2, name: 'Wacher' }
                    ];

Again here, you can pick and choose which type annotation you'd like to have.

Sign up to request clarification or add additional context in comments.

2 Comments

and where do I write this interface code? inside angular class ? or outside class? and if i write outside the class then do i need to extend this interface?
Answers, respectively: Wherever it belongs (probably at top-level in a file), no, no, and no

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.