Kiran Yallabandi Kiran Yallabandi - 10 months ago 49
TypeScript Question

What is Type in angular 2?

I have come across the

keyword at many places in the documentation. For example as seen here
has the
property. It is said to be of type
. 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
does. Am I missing something basic ??

Answer Source

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