简体   繁体   中英

Typescript: return type of generic type

I need to translate this java concept:

public interface Expression<T> {
  Class<? extends T> getType();
}

Is there any way to get it or something similar?

In javascript you have typeof operator. For example, typeof "Jon" will return "string". In your case, typeof function getType(){} will return "function"

Like @savinn mentioned, there is the typeof operator which returns a string representation, but you can also access the .constructor member as well .

The caveats are

  1. that this only gives you the constructor function, but generics aren't preserved in any way, so you'll likely get Array from a number[] , but no information about the element type number will be available.
  2. It might not give you what you want for primitives: $> 123 instanceof (123).constructor $< false $> new Number(123) instanceof (123).constructor $< true

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