In Typescript, optional parameters are indicated by a question mark.
However, I have only found one way to instantiate the class using the new keyword.
Interestingly, in Angular 2's "hero" tutorial, classes are not instantiated with the new keyword; this is internally handled by Angular.
For example, consider the following code snippets:
models/users.ts
export class User {
id: number;
name?: string; // Making 'name' optional
}
models/mock-users.ts
import {User} from './user';
export const USERS: User[] = [
{
id: 1
// No name specified (making it optional for user with id 1)
},
{
id: 2,
name: "User 2"
},
]
services/user.service.ts
import {Injectable} from 'angular2/core';
import {USERS} from './../models/mock-users';
@Injectable()
export class UserService {
getUsers() {
return Promise.resolve(USERS);
}
}
views/my-component.component.ts
// Other imports...
@Component({
// ...
})
export class MyComponent {
constructor(private _userService: UserService) { }
getUsers() {
this._userService.getUsers().then(users => console.log(users));
}
}