Angular 2 FormBuilder types

2.9k views Asked by At

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.

1

There are 1 answers

3
Amit kumar On

Forms in angular are of two types

  1. template driven

and

  1. reactive forms ( that use FormGroup/FormBuilder ).

According to me Reactive forms are good because of custom validation option and can create dynamic forms. these two feature make reactive form more powerfull.

reactive form link Angular2 reactive form confirm equality of values

and i think for observables we already use type Observable <person[]> ;

for each object we can define its interface and use in component.

but yes using mapped Types we will get more options like readonly, proxies....

and nodbody talking about mapped types is because its in TypeScript 2.1 but for our angular app we are using "typescript": "~2.0.10" for keeping our app stable.

Mapped Types

One common task is to take an existing type and make each of its properties entirely optional. Let's say we have a `Person:

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

A partial version of it would be:

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

with Mapped types, PartialPerson can be written as a generalized transformation on the type Person as:

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

type PartialPerson = Partial<Person>;

Mapped types are produced by taking a union of literal types, and computing a set of properties for a new object type. They're like list comprehensions in Python, but instead of producing new elements in a list, they produce new properties in a type.

In addition to Partial, Mapped Types can express many useful transformations on types:

// 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 }
    };