TypeScript: interface vs Class vs Modules vs Program vs Function

I read the TypeScript specification located at: http://www.typescriptlang.org/Content/TypeScript%20Language%20Specification.pdf

However, this confused me with the following:

  • Interface
  • Class
  • Modules
  • Programs
  • Function.
  • Declare vs var

Can someone briefly help you understand which one should be used when? Is the interface and class the same as the C # version?

+51
typescript
Oct. 06
source share
1 answer

I replied that these answers coincide with C #, as you mentioned in your question, but I hope the answers are useful for people coming to TypeScript from similar languages.

Interface

The interface in TypeScript is similar to the interface you met in C #. This is a contract - if one of your classes implements an interface, it promises has certain properties or methods that interface documents.

In TypeScript, an interface can inherit from another interface to extend it from the class to capture its implementation.

Whenever something seems impossible in TypeScript, you can usually solve it using the interface!

TypeScript interfaces have a wide range of uses. They describe the structure, so it can be used wherever you use the type (i.e., not only to implement them in the class, you can use them to enter variables, parameters, return values, etc.).

Class

This is very similar to the concept of a class in C #. You can inherit from other classes to extend or specialize behavior.

Namespace

The newer namespace keyword is used to place a group of code in a restricted area. This is similar to C # namespaces.

Module

Modules are better than namespaces when it comes to TypeScript. A module (formerly known as an external module) is a file that is self-contained and adds nothing to your global scope. You can load modules into local variables as needed. Modules provide a good way to organize code and load parts on demand. When using modules, it is best to avoid using namespaces. Modules are better than namespaces.

Program

The program is a set of modules, classes. This is essentially what you wrote using TypeScript.

Function / method

Classes contain methods, and you can also write autonomous functions that are not related to the class.

Declare against var

var creates a new variable. declare used to indicate to TypeScript that the variable was created elsewhere. If you use declare , nothing is added to the generated JavaScript - this is just a hint to the compiler.

For example, if you are using an external script that defines var externalModule , you should use declare var externalModule to prompt the TypeScript compiler that externalModule already configured.

+112
Oct 06
source share



All Articles