Posted by : Darko Borojevic - contact me
.tsextension at the end.
TypeScript class inheritance example with different member types
Access modifiersTypescript 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.
Variable with any type declarationWe can use any type in functions too:
Function with any type argument and return statementA 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
Tas seen below), to enable enhanced type checking. The type parameter can be 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 optional. Below, we have transformed a class
Vehicle_1that extends the
Carclass, in such a way that we give the returnType() function optional boolean parameter. After that, we check that parameter with an
elseifloop, and set the value of Functional variable accordingly.