Sergey Nivens - Fotolia
For a competent Java developer, TypeScript syntax is relatively straightforward. Like Java, TypeScript syntax has mechanisms to define enums, iterative loops, methods, classes and constructors. None of these topics are foreign to anyone who has knowledge of the javac utility. But while the key concepts are all the same, the TypeScript syntax is decidedly different. This can make transitioning from Java to TypeScript a frustrating experience, as tasks once simple in Java can trigger esoteric errors when you compile the corresponding TypeScript.
To make the transition from Java to TypeScript a little bit easier, we've provided a quick TypeScript syntax guide for Java developers here.
The goal of this TypeScript syntax tutorial is not to describe every aspect of the language, but instead to demonstrate how concepts familiar to a Java developer manifest themselves in TypeScript. Most Java developers can write pretty impressive programs using language constructs such as variables, classes, conditional statements, iterative logic and methods.
TypeScript variable declaration syntax
For both fractions and whole numbers, TypeScript uses the number type. For text, TypeScript uses the string type, and for true or false values, it uses boolean.
Declaring a TypeScript enum
For a Java developer, a confusing aspect of the enum is that, when referenced directly, the output is the zero-based index of the element. To get the actual value of an element of the enum, a reference to the index of the element must be provided. It's somewhat counterintuitive.
Declaring arrays in TypeScript is very similar to Java, with the exception that the name of the array and the associated data type are stated in reverse.
The TypeScript let..of iterative loop
There is a special let syntax, however, for looping through collections. For the Java developer learning TypeScript, the syntax is analogous in many ways to the for..each loop, which was introduced with Java 5.
Conditional statements in TypeScript
Java methods and TypeScript functions
Java has methods, while TypeScript has functions. The two concepts are identical. It's only the syntax that is different.
When compared to TypeScript, the key differences are:
- The word function appears in the name of the method.
- The return type appears after the arguments.
- The name and type of the arguments are reversed when Java methods and TypeScript functions are compared.
Declaring Java and TypeScript classes
Both TypeScript and Java embrace the concept of a class in order to implement object-oriented concepts. Similarities between the two include the fact that classes can have methods, constructors and variables, although each of these items are declared in a slightly different way. The following example shows the difference between declaring a simple Java class and a simple TypeScript class.