Kiran Yallabandi Kiran Yallabandi - 2 months ago 6
TypeScript Question

What is Type in angular 2?

I have come across the

Type
keyword at many places in the documentation. For example as seen here
ComponentRef
has the
componentType
property. It is said to be of type
Type<any>
. On further searching I find this entry about it on the docs. It says: Invoke as ES7 decorator.

Also on looking up the source on github , I find these comments :

/**
* @whatItDoes Represents a type that a Component or other object is instances of.
*
* @description
*
* An example of a `Type` is `MyCustomComponent` class, which in JavaScript is be represented by
* the `MyCustomComponent` constructor function.


However I am still not clear as to what
Type
does. Am I missing something basic ??

Answer

Judging by the definition:

export const Type = Function;

export interface Type<T> extends Function {
    new (...args: any[]): T;
}

Type is just a function. Type<T> is just some function/type when constructed (using any combination of arguments), creates a T. So in other words, a "type" definition. Remember, "types" in javascript (in the OO sense) are represented using functions. And that equates to classes, interfaces and the like in typescript.

Given that, the following should hold:

class Foo {
    s: string;
}
class Bar {
    s: number;
}
class Biz {
    ss: string;
}
class Baz {
    s: string;
    t: number;
}

let x: Type<{ s: string }>; // x is a type that returns an object
                            // with an s property of type string

x = Foo; // ok
x = Bar; // error, s is not a string
x = Biz; // error, doesn't contain s property
x = Baz; // ok
x = { s: "foo" }; // haha nice try