How to set optional class parameters in Angular 2-Typescript?

I know in Typescript optional parameters can be marked by question mark.

However, the only way I found to actually instantiate the class with new keyword.

The thing is that based on Angular 2’s starter “hero” tutorial classes are not instantiated via the new keyword and as far as I understood that’s internally done by Angular.

For example I have this code:


export class User {
    id: number;
    name: string; // I want this to be optional


import {User} from './user';

export var USERS: User[] = [
       id: 1
       // no name (I wanted it to be optional for user with id 1)
       id: 2,
       name: "User 2"


import {Injectable} from 'angular2/core';
import {USERS} from './../models/mock-users';

export class UserService {
    getUsers() {
         return Promise.resolve(USERS);


// imports here...

   // ...

export class MyComponent {
   constructor(private _userService: UserService) { }

   getUsers() {
         this._userService.getUsers().then(users => console.log(users));

Leave a Reply

3 Comment threads
0 Thread replies
Most reacted comment
Hottest comment thread
1 Comment authors
Jason Recent comment authors
newest oldest most voted
Notify of

In your case, it might be more convenient to use an interface for User instead. export interface User { id: number; name?: string; // interfaces allow fields to be optional } I use interfaces when I want to define the ‘shape’ of an object, classes when I need to add behavior (methods). If all you need is to move data around, I’d use an interface. If you do need a class, then the syntax for creating instances of Users in mock-users.ts should be a bit different. Firstly, there’s no “optional class fields” in TypeScript. Any field can be not set/’undefined’,… Read more »

class User {
    constructor(public id: number, public name: string = null) {}

var USERS: User[] = [
    new User(1),
    new User(2, 'User 2')



Using a constructor will probably make your life a lot easier. You won’t get undefined when you try to get a User’s name and you’ll be able to define functions on the class. The only difference is that you’d use new User(...) instead of just using an object literal as a type.


One other way is to use Object.assign to extend a valid typed object with the property you only need (omitting property a and c in this example) export class A { a:number=1; b:number; c:string; d:string; } let validA:A = Object.assign(new A(),{ b:3, d:'Lorem ipsum' }); I personnaly prefer this syntax to avoid multiline object initialisation and the boring thing to create an interface (so another file quite useless if a coresponding class exists) for each model of my app. In addition, don’t hesitate to set default value in your class definition, even if it’s not mandatory for this case. One… Read more »