Web-Typescript other types

Other Typescript types

        So far, we've covered basic Typescript features. Unfortunately, there are many more advanced Typescript features you may encounter. Now, let's take a brief look at some of the features you may encounter in the remainder of this unit. Remember, this is not a Typescript unit. Our goal is to get to the point where JavaScript frameworks can be used for web development.

Union Types

        Union types allow us to specify a type that accepts two or more other types. Use the '|' operator to create union type declarations. For example, the following function accepts a single parameter of type string or number.

function primitive(x: number | string): string {
    if (typeof x == "number") {
    return "number";
    } else {
    return "string";
    }
  }

        In union types we are not limited to just two types. For example, we can add a Boolean type parameter to the above definition as shown below.

  function primitive2(x: number | string | boolean): string {
    if (typeof x == "number") {
      return "number";
    } else if (typeof x == "string"){
      return "string";
    } else {
      return "boolean";
    }
  }

Type assertion and type conversion

        Type conversion at runtime is necessary to achieve type-safe conversion of object types. Type conversion is required when a more general type needs to be converted to a specific type in order to access properties or methods associated with that type. In the Typescript code associated with the web page, we encounter this situation when we access the DOM object.

        You may have seen type conversion in object-oriented languages ​​like Java or C#. In Java and C#, we write explicit type conversions by enclosing the new type in parentheses, which is called type conversion. In Typescript we use a different syntax. We use angle brackets '<' and '>', often called type assertions.

        For example, suppose we wish to resize an HTMLElement object to an HTMLInputElement object. This happens quite often, and we'll explain it further in the tutorial. The code example is as follows:

  let elt = document.getElementByID('element1');
  let val1 = <HTMLInputElement>elt.value;

        In this case, calling getElementById() returns an object of type HTMLElement. This object does not contain a value attribute. However, a subclass of HTMLElement is HTMLInputElement, which represents a tag in HTML that contains a value attribute. Before we try to access this property, we must cast the class to the appropriate type. Note that this conversion happens at runtime, so if an error occurs (e.g. val1 is not of type HTMLInputElement), a runtime error will result.
        We'll leave the type conversion example in the tutorial session so you can see its effect dynamically in your own code.
        Next, we'll look at DOM elements and type conversion.

Use DOM types

        One of the useful things we want to do is access web widgets and the data they contain. For example, if we have a text input field, then at some stage we want to extract the text entered by the user. In JavaScript we can do this simply, for example for an HTML element:

<input id="field1">

        We can extract text using JavaScript code:

var f1 = document.getElementById("field1").value;

        This does not translate to Typescript. The Typescript compiler will give the following error:

error TS2339: Property 'value' does not exist on type 'HTMLElement'.

        The problem here is that the getElementById() method returns an object without a value property. As the error message implies, the return object of this method has type HTMLElement. Type HTMLElement represents all DOM elements, including elements representing text input fields. Technically, HTMLElement is a superclass that represents all DOM elements, this example is for subclassing a specific element type. The value attribute is implemented in a subclass named HTMLInputElement. This is the difference between Javascript's dynamic typing (looking up properties at runtime) and Typescript's static typing (checking types at compile time and before execution).

        So what must we do? As with most object-oriented languages ​​such as Java or C#, we need to convert the superclass type object to the subclass type HTMLInputElement at runtime so that we can check that the object is of the correct type. Typescript performs type conversion by enclosing the type in "<" and ">" and placing this syntax before the object to convert its type. In this example we write:

let f1 = (<HTMLInputElement>document.getElementById("field1")).value;

        If the required parentheses are confusing, we can also write the following two steps:

let f1elt = <HTMLInputElement>document.getElementById("field1");
let f1 = f1elt.value;

        So how do we know what type conversion is needed? Generally, we know that type conversion is required when the property we are accessing is unique to the element we are accessing or does not exist on all DOM objects. In the above example, the value attribute only applies to form widget objects. You can guess the type because in this case the type name has the tag name "Input" inserted between "HTML" and "Element".

Guess you like

Origin blog.csdn.net/qq_54813250/article/details/133611711