.ts extension at the end of the file.
TypeScript classes and types
TypeScript class inheritance example with different member types
TypeScript can use encapsulation for its class members, as any other OOP-paradigm programming language. Three optional modifiers are
private. If you do not use any of these, default is set as public.
The any data type
Variable with the
any type declaration
We can use any type in functions too:
Function with the
any type argument and return statement
A thing to have in mind is that using any, while generic, will cause the function to accept all types for the variable or argument. The information about what that type was when the function returns is lost at compile time, so if we passed in a number, a string, or other, the only information we have is that any type could be returned. To beat this problem, we can use type parameter (big
T as seen below), to enable enhanced type checking. The type parameter can be of any type, just like
any, but it enables the function to catch the T at compile time, and compare it with the return value type of the function and see if both have similar types. This is how we can address the problem of tracking any type at compile time.
? symbol at the end of parameters that we want to be left optional. Below, we have transformed the class
Vehicle_1 that extends the
Car class, in such a way that we give the returnType() function optional boolean parameter. After that, we check that parameter with
elseif loop, and set the value of Functional variable accordingly.
TypeScript class inheritance with optional parameter function
Create Vehicle object and call a function with optional parameter set to false
TypeScript – using an Interface example
In TypeScript we can create arrays by declaring an array of certain type, very much like we do in Java. If you try to use push method to insert a new member of type string to a number array for example, TypeScript compiler will throw type is not assignable error (or something similar) and you will have to insert a proper value previously defined by type. Let’s change our example to replace interface and its members with arrays:
Additionally, we can use and define a Tuple as a type, using a type keyword.
Tuple as type example
Posted on: May 14, 2019
Print article Email article