Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 ??

like image 928
Kiran Yallabandi Avatar asked Oct 07 '16 03:10

Kiran Yallabandi


People also ask

What is type in Angular?

The type keyword defines an alias to a type. type str = string; let cheese: str = 'gorgonzola'; let cake: str = 10; // Type 'number' is not assignable to type 'string'

How do you type in TypeScript?

TypeScript - Type Annotations We can specify the type using :Type after the name of the variable, parameter or property. There can be a space after the colon. TypeScript includes all the primitive types of JavaScript- number, string and boolean. In the above example, each variable is declared with their data type.

What does !: Means in Angular?

This specifically means that if the value you are binding to the view is null then it should return null else the actual value, so that you dont get any issues while rendering the template.

What is notation in Angular?

It is called safe navigation or elvis operator, which checks the value is present. The Angular safe navigation operator (?.) is a fluent and convenient way to guard against null and undefined values in property paths. Here it is, protecting against a view render failure if the user is null.


1 Answers

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
like image 190
Jeff Mercado Avatar answered Oct 04 '22 20:10

Jeff Mercado