Answer the question
In order to leave comments, you need to log in
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>();
Answer the question
In order to leave comments, you need to log in
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;
}
let numbers = convertToArray<number>(5)
let strings = convertToArray<string>('test')
let users = convertToArray<User>(new User())
@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 Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question