How to use Typescript generics to erase styles to implement generics?

So you can’t use something like this?

class Helpers { static ObjectAs<T>(val: any): T { if (!(val instanceof T)) { return null; } return <T>val; } } 

Any workaround for getting the basic type of a generic declaration?

Update 1:

As Ryan Cavanaugh mentioned, when it is compiled, the entire type system is erased, more like an implementation of Java Generics. I believe that the .NET implementation in Generics for storing type information in compiled code is better than Java. However, I cannot help but wonder why it is not possible to allow full runtime checking of typical types and parameters of a type type in TypeScript? Why did TypeScript designers decide to delete all generic information at runtime?

The following TypeScript code:

 function As<T>(n: any): T { if (n instanceof T) { return n; } else { return null; } } var obj: Object = 1; var x = As<number>(obj); 

Can be translated into this JavaScript code:

 function As(n, T) { if (n instanceof T) { return n; } else { return null; } } var obj = 1; var x = As(obj, Number); 

Storing type information at run time and compatible with js code!

Update 2: I posted a question about CodePlex, hoping to get more from TypeScript people https://typescript.codeplex.com/discussions/550262

+6
source share
1 answer

The type system is completely erased. You can see this in the generated code for any general function.

However, for classes, some runtime information remains. You could write this:

 class A { } class B { } function As<T>(n: any, type: { new(...args: any[]): T }): T { if(n instanceof type) { return n; } else { return null; } } var x = new A(); var y = new B(); console.log(As(x, A)); console.log(As(x, B)); 
+5
source

Source: https://habr.com/ru/post/971467/


All Articles