Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What does TypeScript mean?

2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)06/01 Report--

This article mainly shows you "what is the meaning of TypeScript", the content is easy to understand, clear, hope to help you solve your doubts, the following let the editor lead you to study and learn "what does TypeScript mean" this article?

TypeScript is the data type

TypeScript does not have many built-in data types that can be used to declare variables, only strings, numbers, and Boolean. All three types are subtypes of the any type (the any type can also be used when declaring variables). You can set or test variables declared by these four types against null or undefined types. You can also declare these methods as void to indicate that they did not return a value.

This example declares a variable as a string:

Var name: string

You can extend this simple type system with enumerated values and four object types: interfaces, classes, arrays, and functions. For example, the following code defines an interface (an object type) with the name ICustomerShort. The interface contains two members: the property Id and the method CalculateDiscount:

Interface ICustomerShort {Id: number; CalculateDiscount (): number;}

As in C #, when declaring variables, you can use the interface and return the type. This example declares the variable cs as type ICustomerShort:

Var cs: ICustomerShort

You can also define an object type as a class, which, unlike an interface, can contain executable code. This example defines the CustomerShort class using a property and a method:

Class CustomerShort {FullName: string; UpdateStatus (status: string): string {... manipulate status... Return status;}}

Similar to the newer version of C#, you do not need to provide implementation code when defining properties. A simple declaration of this name and type is sufficient. A class can implement one or more interfaces, as shown in figure 1, adding my ICustomerShort interface to my CustomerShort class through its properties.

Figure 1 adds an interface to a class

Class CustomerShort implements ICustomerShort {Id: number; FullName: string; UpdateStatus (status: string): string {... manipulate status... Return status;} CalculateDiscount (): number {var discAmount: number;... calculate discAmount... Return discAmount;}}

As shown in figure 1, the syntax for implementing an interface in TypeScript is as simple as it is in C #. To implement a member of this interface, you only need to add a member with the same name without binding the interface name to the related class member. In this example, I only add Id and CalculateDiscount to the class to implement ICustomerShort. TypeScript also allows you to use object type literals. This code sets the variable cst to the object text that contains a property and a method:

Var csl = {Age: 61, HaveBirthday (): number {return this.Age++;}}

This example uses the object type to specify the return value of the UpdateStatus method:

UpdateStatus (status: string): {status: string; valid: boolean} {return {status: "New", valid: true};}

In addition to object types (classes, interfaces, literals, and arrays), you can also define function types that describe function signatures. The following code overrides the CalculateDiscount of my CustomerShort class to accept a single parameter named discountAmount:

Interface ICustomerShort {Id: number; CalculateDiscount (discountAmount: (discountClass: string, multipleDiscount: boolean) = > number): number}

The parameter is defined using a function type that accepts two parameters (a string parameter and a Boolean parameter) and returns a number. If you are a C # developer, you may find that this syntax looks like a lambda expression.

The class that implements this interface is shown in figure 2.

Figure 2 this class implements the appropriate interface

Class CustomerShort implements ICustomerShort {Id: number; FullName: string; CalculateDiscount (discountedAmount: (discountClass: string, multipleDiscounts: boolean) = > number): number {var discAmount: number;... calculate discAmount... Return discAmount;}}

Similar to the newer version of C #, TypeScript can also infer the data type of the initialization variable from its value. In this example, TypeScript assumes that the variable myCust is CustomerShort:

Var myCust= new CustomerShort (); myCust.FullName = "Peter Vogel"

Similar to caches, you can use an interface to declare a variable, and then set this variable to an object that implements this interface:

Var cs: ICustomerShort;cs = new CustomerShort (); cs.Id = 11tens cs.FullName = "Peter Vogel"

Finally, you can also use type parameters (which look a lot like generics in C #) to make the calling code specify the data type to use. This example allows the code that creates the class to set the data type of the Id property:

Class CustomerTyped {Id: t;}

This code sets the data type of the Id property to a string before using it:

Var cst: CustomerTyped;cst = new CustomerTyped (); cst.Id = "A123"

To isolate classes, interfaces, and other public members and avoid name conflicts, you can declare these constructs in a module similar to the C # namespace. You must use the export keyword to mark these items that you want to provide to other modules. The module in figure 3 exports two interfaces and a class.

Figure 3 exports two interfaces and one class

Module TypeScriptSample {export interface ICustomerDTO {Id: number;} export interface ICustomerShort extends ICustomerDTO {FullName: string;} export class CustomerShort implements ICustomerShort {Id: number; FullName: string;}

To use the exported component, you can prefix the component name with the module name, as shown in the following example:

Var cs: TypeScriptSample.CustomerShort

Alternatively, you can use the TypeScript import keyword to create a shortcut to this module:

Import tss = TypeScriptSample;...var cs:tss.CustomerShort;TypeScript is very flexible in data typing

If you are a C # programmer, you should be familiar with all of this except for possible variable declaration inversion (variable name comes first, data type comes after) and object literal. However, almost all data typing in TypeScript is optional. This specification describes the data type as "comment". If you omit the data type (and TypeScript cannot infer this data type), the data type defaults to the any type.

TypeScript also does not require strict matching of data types. TypeScript uses a feature of the specification called "structural subtyping" to determine compatibility. This is similar to the function commonly referred to as "duck typing". In TypeScript, if two classes have members of the same type, they are considered the same. For example, the following is a Customer ­Short class that implements the ICustomerShort interface:

Interface ICustomerShort {Id: number; FullName: string;} class CustomerShort implements ICustomerShort {Id: number; FullName: string;}

Here is a CustomerDeviant class similar to my CustomerShort class:

Class CustomerDeviant {Id: number; FullName: string;}

With structural subtyping, I can use CustomerDevient with variables defined using my CustomerShort class or ICustomerShort interface. These examples use CustomerDeviant interchangeably with variables declared as CustomerShort or ICustomerShort:

Var cs: CustomerShort;cs = new CustomerDeviantcs.Id = 11ash var csi: ICustomerShort;csi = new CustomerDeviantcsi.FullName = "Peter Vogel"

This flexibility allows you to assign TypeScript object literals to variables declared as classes or interfaces, assuming they are structurally compatible, as shown in the following example:

Var cs: CustomerShort;cs = {Id: 2, FullName: "Peter Vogel"} var csi: ICustomerShort;csi = {Id: 2, FullName: "Peter Vogel"}

This introduces TypeScript-specific features about obvious types, parent types, and subtypes that lead to common problems with distributability, which is skipped in this article. For example, these features will allow CustomerDeviant to have members that do not exist in CustomerShort without causing my sample code to fail.

TypeScript owns classes

The TypeScript specification calls the language an implementation of "class patterns that implement many variants [using] prototype chains on object-oriented inheritance mechanisms." In fact, this means that TypeScript is not just data typed, but object-oriented efficiently.

Just as the C # interface can inherit from the base interface, the TypeScript interface can extend another interface in the same way, even if the other interface is defined in another module. This example extends the ICustomerShort interface and creates a new interface called ICustomerLong:

Interface ICustomerShort {Id: number;} interface ICustomerLong extends ICustomerShort {FullName: string;}

The ICustomerLong interface will have two members: FullName and Id. In the merged interface, the members from this interface are displayed first. Therefore, my ICustomerLong interface is equivalent to this interface:

Interface ICustomerLongPseudo {FullName: string; Id: number;}

Classes that implement ICustomerLong will need these two properties:

Class CustomerLong implements ICustomerLong {Id: number; FullName: string;}

Classes can extend other classes by extending another interface with an interface. The class in figure 4 extends CustomerShort and adds new attributes to the definition. It uses explicit getter and setter to define properties (although this is not a particularly useful method).

Figure 4 attributes defined using getter and setter

Class CustomerShort {Id: number;} class CustomerLong extends CustomerLong {private id: number; private fullName: string; get Id (): number {return this.id} set Id (value: number) {this.id = value;} get FullName (): string {return this.fullName;} set FullName (value: string) {this.fullName = value;}}

TypeScript adopts the best practice of accessing internal fields such as id and fullName by referencing this class (this). These classes can also have constructors that contain the functionality just adopted by C#: automatically define fields. The constructor in the TypeScript class must be named the constructor, and its public parameters are automatically defined as properties and initialized from the values passed to those properties. In this example, the constructor will accept a single parameter named Company of type string:

Export class CustomerShort implements ICustomerShort {constructor (public Company: string) {}

Because the Company parameter is defined as public, this class also gets a public property named Company initialized from the value passed to the constructor. With this feature, the variable comp will be set to "PH&VIS", as shown in this example:

Var css: CustomerShort;css = new CustomerShort ("PH&VIS"); var comp = css.Company

Declaring the parameters of the constructor private creates an internal property that can only be accessed from code within a class member through the keyword this. If this parameter is not declared public or private, no property is generated.

Your class must have a constructor. As in C #, if you do not provide a constructor, the system will provide you with one. If your class extends other classes, any constructor you create must contain a call to super. The constructor on the class being extended will be called. This example includes a constructor with a super call that provides parameters to the constructor of the base class:

Class MyBaseClass {constructor (public x: number, public y: number) {}} class MyDerivedClass extends MyBaseClass {constructor () {super (2 TypeScript 1);}} TypeScript inherits in different ways

Similarly, if you are a C # programmer, you will be familiar with all of this except for some interesting keywords (extends). But again, the extension class or interface is not exactly the same as the inheritance mechanism in C#. The TypeScript specification uses general terms for the extended class ("base class") and the class that extends it ("derived class"). However, for example, this specification calls a class "inheritance specification" instead of the word "inheritance".

First of all, when defining a base class, TypeScript has fewer options than C#. You cannot declare a class or member as irreplaceable, abstract, or virtual (although the interface provides much of the functionality provided by the virtual base class).

There is no way to prevent some members from being inherited. Derived classes inherit all members of the base class, including public and private members (all public members of the base class are replaceable and private members are irreplaceable). To replace a public member, simply define a member in a derived class with the same signature. Although you can use the super keyword to access public methods from a derived class, you cannot use super to access a property in the base class (although you can replace this property).

TypeScript allows you to add an interface simply by declaring the interface with the same name and new member. This allows you to extend existing JavaScript code without creating new named types. The example in figure 5 defines the ICustomerMerge interface through two separate interface definitions, and then implements the interface in the class.

Figure 5 ICustomerMerge interface defined by two interface definitions

Interface ICustomerMerge {MiddleName: string;} interface ICustomerMerge {Id: number;} class CustomerMerge implements ICustomerMerge {Id: number; MiddleName: string;}

These classes can also extend other classes, but not interfaces. In TypeScript, interfaces can also extend classes, but can only be implemented in a way that involves inheritance. When an interface extends a class, the interface includes all class members (public and private), but does not include the implementation of this class. In figure 6, the ICustomer interface will have the private member id, the public member Id, and the public member MiddleName.

Figure 6 extension class with all members

Class Customer {private id: number; get Id (): number {return this.id} set Id (value: number) {this.id = value;}} interface ICustomer extends Customer {MiddleName: string;}

The ICustomer interface is so limited that you can only use it with classes that extend the class that the interface extends (in this case, the Customer class). TypeScript requires you to include private members in the interface that you want to inherit on the class that you want to extend from this interface, rather than on the interface that is reimplemented in the derived class. For example, a new class that uses the ICustomer interface needs to provide an implementation for MiddleName (because MiddleName is only specified in this interface). Developers using ICustomer can choose to inherit from the Customer class or replace public methods, but cannot replace private id members.

This example shows a class (called NewCustomer) that implements the ICustomer interface and extends the Customer class as needed. In this example, NewCustomer inherits the implementation of Id from Customer and provides an implementation for MiddleName:

Class NewCustomer extends Customer implements ICustomer {MiddleName: string;}

This combination of interfaces, classes, implementations, and extensions provides a controlled way for you to define classes that extend classes defined in other object models (for more information, see part 7.3 of the language specification, "interfaces to extended classes"). Coupled with TypeScript's ability to use information about other JavaScript libraries, TypeScript allows you to write TypeScript code that works with objects defined in those libraries.

TypeScript knows about your library

In addition to learning about the classes and interfaces defined in your application, you can provide TypeScript with information about other object libraries. It can be processed through the TypeScript declaration keyword. This creates an "environment declaration" as referred to by the specification. You may never need to use the declaration keyword yourself, because you can find the definition files for most JavaScript libraries on the DefinitelyTyped site (definitelytyped.org). With these definition files, TypeScript can efficiently "read the documentation about the libraries you need to use."

Of course, "reading documentation" means that you will get IntelliSense support for data typing and compile-time checking when using the objects that make up the library. In some cases, this also allows TypeScript to infer the type of variable from the context in which it is used. With the help of the lib.d.ts definition file provided with TypeScript, TypeScript assumes that the type of variable positioning tag is HTMLAnchorElement in the following code:

Var anchor = document.createElement ("a")

When the createElement method passes the string "a", this definition file specifies that this is the result returned by this method. For example, knowing that the locator is HTMLAnchorElement means that TypeScript knows that the locator variable will support the addEventListener method.

The TypeScript data type interface also applies to parameter types. For example, the addEventListener method accepts two parameters. The second is a function in which addEventListener passes an object of type PointerEvent. TypeScript knows this and supports access to the cancelBubble property of the PointerEvent class in this function:

Span.addEventListener ("pointerenter", function (e) {e.cancelBubble = true;})

Other JavaScript definition files provide similar functionality in the way lib.d.ts provides HTML DOM-related information. For example, after adding the backbone.d.ts file to my project, I can declare a class that extends the Backbone Model class and implements my interface with the following code:

Class CustomerShort extends bb.Model implements ICustomerShort {}

If you are interested in more information about how to use TypeScript with Backbone and Knockout, please check out my practical TypeScript column (bit.ly/1BRh8NJ). In the new year, I will take a closer look at how to use TypeScript in conjunction with Angular.

TypeScript does much more than that. In the future, TypeScript version 1.3 must include union data types (for example, to support functions that return lists of specific types) and aggregations. The TypeScript team is working with other teams that apply data typing to JavaScript (Flow and Angular) to ensure that TypeScript can be used with as many JavaScript libraries as possible.

If you need to perform operations that are supported by JavaScript but not allowed by TypeScript, you can always integrate your JavaScript code because TypeScript is a superset of JavaScript.

The above is all the contents of this article "what does TypeScript mean?" Thank you for reading! I believe we all have a certain understanding, hope to share the content to help you, if you want to learn more knowledge, welcome to follow the industry information channel!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report