|Getting Started With TypeScript|
|Written by Mike James|
|Thursday, 12 April 2018|
Page 3 of 3
It is well known that you can arrange for inheritance using classes. You can do the same thing with interfaces:
Now myDerivedInterface is a type that includes all of the methods and properties of myInterface. Objects of type myDerivedInterface can be used in place of objects of type myInterface.
and you can assign test to a variable of type myInterface
Following this you can't access test2.j as this is not a member of myInterface.
If you are familiar with the ideas of base and derived type is is all very obvious. However notice that type in this case is defined as the collection of methods and properties that an object actually has at any given point in the program.
defines an object that has more than is needed to be a myInterface type. However as test is of type myInterface you can't access j which isn't part of the interface. You can't even assign test to test2 as in:
because the assignment takes account of the declared types. However, you can use a type assertion, which works very much like a cast in C++ and C#, to force the assignment:
and now you can get at property j.
At this point you are probably thinking that types are great, but you have to put in a lot of work if you want to use types with HTML elements and the DOM. The good news is that there are a lot of predefined types included in with the system. There are types for all of the DOM elements and a great many for CSS and other objects. This makes the whole typing system much more useful than it would be if you really did have to start from scratch.
The type system does catch errors at compile time but they are mostly trivial errors that are easy to find. The overhead of having to jump though hoops to be able to do something doesn't really seem worth it. Better spend the time on writing tests.
A Programmers Guide To Languages
If you want to try out an in-browser version visit: Playground
or email your comment to: firstname.lastname@example.org
|Last Updated ( Thursday, 12 April 2018 )|