K
K
kachurinets2018-05-28 14:18:31
Angular
kachurinets, 2018-05-28 14:18:31

What's the difference between a normal type specification (through a colon) and a generic type?

I often see in examples that types are specified through generics.
For example so

@Output() ingredientAdded = new EventEmitter<Ingredient>();

I didn’t understand in which cases it is necessary to specify the type through a generic, and in which simply through a colon? If any difference?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dmitry Eremin, 2018-05-28
@kachurinets

it's not the same thing
with :
you're saying what type the variable is or what the method returns
eg
name: string
age: number
getAge() : namber {}
----------------- --------------------------
Generic is more complicated for the other
In your example, the variable ingredientAdded is of type EventEmitter
i.e. true
ingredientAdded : EventEmitter
but
the EventEmitter itself must contain some type of data (here - Ingredient)
In fact, the EventEmitter can accept primitives or objects and its work will be unchanged
--------------- ----------------------------
Generics are nice when you want to define some kind of logic without being tied to a data type. What does it mean?
Suppose I want a method that will take anything as input (string, number, object, etc.), and return an array of this anything

function convertToArray<T>(arg: T): T[] {
    let arr: T[];
//здесь логика заполнения этого массива
    return arr;
}

now i can call
let numbers =  convertToArray<number>(5)
let strings = convertToArray<string>('test')
let users = convertToArray<User>(new User())

Now I have one method that does the same thing but with different data types
------------------------------- ------------
Getting back to the EventEmitter. The emitter creates an event and holds inside some data of the given type
if you do
@Output() ingredientAdded = new EventEmitter<Ingredient>();
, now you can call ingredientAdded.emit(myIngredient)by passing an instance of the Ingredient class to the emit, and not a boolean, for example
------------------------------ -------------
In general, the topic of generics is quite common (Java, C#, TypeScript...), I advise you to pay attention to it

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question