简体   繁体   中英

What does the TypeScript type parameter refer to?

I'm trying to figure out exactly what the "type parameter " is typing in functions with this syntax.

getStuff<T>(id: string): Observable<T> {
  return id;
}

Does the <T> in getStuff<T> refer to the parameter type being passed into the function, or the return value type?

I have already reviewed the TypeScript docs about generics but I still couldn't get a definitive answer.

The <T> in the function declaration will refer to any other T in the function.

In this case, the only other T is in the return type of the function Observable<T> , meaning that it the function will return a value of type Observable<T> .


getStuff<T>(id: string): Observable<T>

getStuff is the name of the function.

<T> indicates that it is a generic function that will use a generic type T throughout the function when referenced.

id is the name of the parameter.

: string indicates that the parameter's type is a string .

: Observable<T> indicates that the return type of the function.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM