TypeScript Features

Now that producing JavaScript from TypeScript code has been de-mystified, some ofits features can be described and experimented with.

  • Types
  • Interfaces
  • Shapes
  • Decorators

    Types

Many people do not realize it, but JavaScript does in fact have types, they'rejust "duck typed", which roughly means that the programmer does not have to thinkabout them. JavaScript's types also exist in TypeScript:

  • boolean (true/false)
  • number integers, floats, Infinity and NaN
  • string characters and strings of characters
  • [] Arrays of other types, like number[] or boolean[]
  • {} Object literal
  • undefined not set
    TypeScript also adds

  • enum enumerations like { Red, Blue, Green }

  • any use any type
  • void nothing
    Primitive type example:
  1. let isDone: boolean = false;
  2. let height: number = 6;
  3. let name: string = "bob";
  4. let list: number[] = [1, 2, 3];
  5. let list: Array<number> = [1, 2, 3];
  6. enum Color {Red, Green, Blue};
  7. let c: Color = Color.Green;
  8. let notSure: any = 4;
  9. notSure = "maybe a string instead";
  10. notSure = false; // okay, definitely a boolean
  11. function showMessage(data: string): void {
  12. alert(data);
  13. }
  14. showMessage('hello');

This illustrates the primitive types in TypeScript, and ends by illustratinga showMessage function. In this function the parameters have specific typesthat are checked when tsc is run.

In many JavaScript functions it's quite common for functions to take optionalparameters. TypeScript provides support for this, like so:

  1. function logMessage(message: string, isDebug?: boolean) {
  2. if (isDebug) {
  3. console.log('Debug: ' + message);
  4. } else {
  5. console.log(message);
  6. }
  7. }
  8. logMessage('hi'); // 'hi'
  9. logMessage('test', true); // 'Debug: test'

Using a ? lets tsc know that isDebug is an optional parameter. tscwill not complain if isDebug is omitted.

原文: https://angular-2-training-book.rangle.io/handout/features/typescript_features.html