3

Learning Angular 2, I first saw ngModel, and now saw FormGroup/FormBuilder which would be better to make complex forms. But I noted that with FormBuilder we lose all the static type power given by TypeScript.

All observables and the main object are typed as any. Is there something that could be done to avoid that?

In relation to that, I saw that TypeScript 2.1 has "mapped types" which in my opinion would be something good to transform a standard interface in a interface of observables without lose the properties types, but I see nobody talking about this for Angular.

4

1 回答 1

3

角度形式有两种类型

  1. 模板驱动

  1. 反应形式(使用 FormGroup/FormBuilder )。

根据我的说法,响应式表单很好,因为自定义验证选项可以创建动态表单。这两个特性使反应形式更加强大。

反应形式链接Angular2反应形式确认值相等

我认为对于 observables 我们已经使用 typeObservable <person[]> ;

对于每个对象,我们可以定义其接口并在组件中使用。

但是是的,使用映射类型我们将获得更多选项,如只读、代理......

nodbody 谈论映射类型是因为它在 TypeScript 2.1 中,但对于我们的 Angular 应用程序,我们使用它"typescript": "~2.0.10"来保持我们的应用程序稳定。

映射类型

一项常见任务是采用现有类型并使其每个属性完全可选。假设我们有一个`Person:

interface Person {
    name: string;
    age: number;
    location: string;
}

它的部分版本是:

interface PartialPerson {
    name?: string;
    age?: number;
    location?: string;
}

使用映射类型,PartialPerson 可以写成 Person 类型的广义转换:

type Partial<T> = {
    [P in keyof T]?: T[P];
};

type PartialPerson = Partial<Person>;

映射类型是通过结合文字类型和计算新对象类型的一组属性来生成的。它们就像 Python 中的列表推导式,但不是在列表中生成新元素,而是在类型中生成新属性。

除了 Partial 之外,映射类型还可以表达许多有用的类型转换:

// Keep types the same, but make each property to be read-only.

    type Readonly<T> = {
        readonly [P in keyof T]: T[P];
    };

// Same property names, but make the value a promise instead of a concrete one

    type Deferred<T> = {
        [P in keyof T]: Promise<T[P]>;
    };

// Wrap proxies around properties of T

    type Proxify<T> = {
        [P in keyof T]: { get(): T[P]; set(v: T[P]): void }
    };
于 2016-12-21T01:15:19.740 回答