我知道在 Typescript 中可选参数可以用问号标记。
但是,我发现使用 new 关键字实际实例化类的唯一方法。
问题是,基于 Angular 2 的入门“英雄”教程类未通过 new 关键字实例化,据我所知,这是由 Angular 内部完成的。
例如我有这段代码:
models/users.ts
export class User {
id: number;
name: string; // I want this to be optional
}
models/mock-users.ts
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"
},
]
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
// imports here...
@Component({
// ...
})
export class MyComponent {
constructor(private _userService: UserService) { }
getUsers() {
this._userService.getUsers().then(users => console.log(users));
}
}
最佳答案
在您的情况下,使用 User 接口(interface)可能更方便。
export interface User {
id: number;
name?: string; // interfaces allow fields to be optional
}
当我想定义对象的“形状”时我使用接口(interface),当我需要添加行为(方法)时我使用类。如果您只需要四处移动数据,我会使用一个接口(interface)。
如果您确实需要一个类,那么在 mock-users.ts
中创建用户实例的语法应该有点不同。首先,TypeScript 中没有“可选类字段”。任何字段都不能设置/'未定义',因此将字段标记为可选是没有意义的。您可以使用 new
关键字实例化一个类 - 缺点是您需要编写构造函数来设置字段值或将实例分配给变量并设置字段。但是使用 new 关键字并没有错,尤其是对于测试对象。
您还可以像在 mock-users.ts
中所做的那样使用对象字面量实例化对象 - 您需要通过添加强制转换来更加明确。
export var USERS: User[] = [
<User> { // explicit cast to let the TypeScript compiler know you know what you're doing
id: 1
// no name (I wanted it to be optional for user with id 1)
},
{
id: 2,
name: "User 2"
},
]
如果没有转换,TypeScript 编译器将产生错误。这是设计来捕捉错误。如果您想了解更多(有趣的)原因,这里有一个关于类型检查背后的一些思考的相关详细讨论:
关于typescript - 如何在 Angular 2-Typescript 中设置可选的类参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36746806/