Type Annotations
Using Java types in TypeScript.
The important thing to note about TypeScript is that none of our types matter, at least as far as the runtime is concerned. Only the type checker looks at it, to help make our code more readable.
However, Java types do matter. If we're defining a new method in Java from TypeScript, we need to define the type for the method.
This is where type annotations come in. Let's take these three types: String
, ArrayList
and HashMap
.
Anywhere where we need to specify a Java type, we use a type annotation.
Here's an example of a type annotation. We can use the imported type itself as a type annotation if it doesn't have any generics that we're required to specify.
When we need to specify generics, we use the .type
method.
And that's it. Type Annotations are useful for when you manually convert a JS type to a specific Java type (i.e. turning an object into a HashMap), or when you're trying to extend types with new methods or constructors.
Last updated