如何在Angular 2-Typescript中设置可选的类参数? [英] How to set optional class parameters in Angular 2-Typescript?

查看:200
本文介绍了如何在Angular 2-Typescript中设置可选的类参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道在Typescript中的可选参数可以通过问号进行标记.

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

但是,这是我发现使用 new 关键字实际实例化类的唯一方法.

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

问题是,根据Angular 2入门级英雄"教程类,不会通过new关键字实例化,据我所知,这是Angular内部完成的.

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.

例如,我有以下代码:

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界面可能更方便.

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.

如果确实需要一个类,则在mock-users.ts中创建Users实例的语法应有所不同.首先,TypeScript中没有可选类字段".不能设置/未定义任何字段,因此将字段标记为可选是没有意义的.您可以使用new关键字实例化一个类-缺点是您需要编写一个构造函数来设置字段值或将实例分配给变量并设置字段.但是使用new关键字并没有错,尤其是对于测试对象.

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', so it doesn't make sense mark a field optional. You can instantiate a class with the new keyword - the downside is that you need to write a constructor to set field values or assign the instance to a variable and set fields. But there's nothing wrong with using the new keyword, especially for test objects.

您也可以像在mock-users.ts中一样用对象常量实例化对象-您需要通过添加强制类型转换来使其更加明确.

You can also instantiate an object with an object literal as you've done in mock-users.ts - you need to be more explicit by adding a cast.

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编译器将产生一个错误.这是设计使错误.如果您想进一步了解(有趣的)原因,下面是有关类型检查背后的一些思想的相关详细讨论:

Without the cast, the TypeScript compiler will produce an error. This is by design to catch a mistakes. If you want to know more about the (interesting) reasons, here's a related detailed discussion on some of the thinking behind the type checking:

https://basarat.gitbooks.io/typescript/content/docs/types/freshness.html

这篇关于如何在Angular 2-Typescript中设置可选的类参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆