K
K
kserg9032020-03-23 16:05:50
typescript
kserg903, 2020-03-23 16:05:50

Why are angle brackets used in function names?

I think I understand why angle brackets are used in the function name, but I would like to make sure that I'm not mistaken. There is the following code:

function identity<T>(arg: T): T {
    return arg;
}
let numberOutput = identity<Number>(1);
console.log(numberOutput); // выведет "1"


The identity function takes a number and returns a number. In this case, the angle brackets serve as a signal to the compiler that the function takes exactly a number.

Thus, if the program has the following function call , then the programmer will notice the error at the compilation stage, and not at runtime. If angle brackets were not used:identity('qwerty')

function identity<T>(arg: T): T {
    return arg;
}
let numberOutput = identity(1);
console.log(numberOutput);


, the programmer would only notice the error at run time.

I correctly understand the purpose of the angle brackets, did not confuse anything?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
Robur, 2020-03-23
@Robur

The identity function takes a number and returns a number.

no, it accepts any type and returns the same type
Thus, if the program has the following call to the identity('qwerty') function, then the programmer will notice the error at compile time, and not at runtime.

There are no errors in this call, everything is fine - it takes a string and returns a string.
, the programmer would only notice the error at run time.

would not notice, because there is no error.
there will be an error if you write
const x: number = identity('aaa')
//или 
const x: string = identity(1)
// или любой другой вариант где типы не совпадут.

You can write it, but it doesn't make sense, it's exactly the same as Read what Generics is in order to have an understanding of "why these brackets are needed" in general. identity<number>(1)identity(1)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question