This is the 15th day of my participation in the November Gwen Challenge. Check out the event details: The last Gwen Challenge 2021
Examples of TypeScript
TypeScript declares merges.Copy the code
A statement to merge
Declaring merge in TypeScript means that the compiler merges two or more separate declarations for the same name into a single declaration. The merged declaration has all the features of the original declaration. Any number of declarations can be combined, not just two declarations.
Declarations in TypeScript create one of three entities: a namespace, a type, or a value. The declaration to create a namespace creates a new namespace that contains the names used with (.) Symbol to use when accessing. The declaration for creating a type is to use the declared model to create a type and bind it to the given name. Finally, the statement that creates the value creates the value you see in the JavaScript output.
Declaration Type | Namespace | Type | Value |
---|---|---|---|
Namespace | x | x | |
Class | x | x | |
Enum | x | x | |
Interface | x | ||
Type Alias | x | ||
Function | x | ||
Variable | x |
Function merge
/ / 1
function print(param1: number, param2: string)
function print(param1: String, param2: number)
function print(param1: any, param2: any) {// Behave differently depending on the type of function argument, which is simply printed hereconsole.log(param1, param2)}Copy the code
Earlier we looked at function overloading, which defines multiple function types.
Interface with
/ / 2
interface User {
firstName: string
lastName: string
}
interface User {
age: number
}
Copy the code
Interface merge is the most common declarative merge. Interface merge combines the members of various interfaces with the same name into one interface. Example 2 is equivalent to Example 3 below:
/ / 3
interface User {
firstName: string
lastName: string
age: number
}
Copy the code
Note: Interface merged members can be duplicated, but the duplicated members must be of the same type. For function members, each function member with the same name is treated as an overload of the same function.
Such merger
The merging of classes is consistent with the merging rules of interfaces.
Namespace merge
/ / 4
namespace Model {
export class Mask {
// todo
}
}
namespace Model {
export interface Show { duration: number; }
export class Content {
// todo}}Copy the code
Namespaces with the same name also merge their members. Interfaces exported by modules with the same name are merged to form a single namespace containing the merged interface. The merged namespace of example 4 is equivalent to example 5:
namespace Model {
export interface Show { duration: number; }
export class Mask {
// todo
}
export class Content {
// todo}}Copy the code
Note: Not everything in TypeScript can be merged; for example, classes cannot be merged with other classes or variables.
Finish this! If this article helps you at all, please give it a thumbs up.