function

The function is JavaScript The foundation of the application , It helps you implement the abstraction layer , Simulation class , Information hiding and module . stay TypeScript in , Although classes are already supported , Namespace and module , But functions are still the main place to define behavior .TypeScript by JavaScript Function adds extra functionality , Let's make it easier to use .

Basic example

and JavaScript equally ,TypeScript Functions can create named functions and anonymous functions . You are free to choose the way that suits the application , Whether it's defining a series of API Function is still a function that is used only once .

//  Name the function 
function add(x, y) {
return x + y
} // Anonymous functions
let myAdd = function(x, y) {
return x + y;
}

Function type

Define a type for a function

Let's add a type to the function above :

function add(x: number, y: number): number {
return x + y
} let myAdd = function(x: number, y: number): number {
return x + y
}

We can add a type to each parameter and then add a return value type to the function itself .TypeScript It can automatically infer the return value type according to the return statement .

Write the complete function type

Now we have specified the type for the function , Let's write out the complete type of the function .

//  The complete writing of functions 
// myAdd2----> Variable name ---- function myAdd2
// (x: number, y: number) => number Is the type of the current function
// function(x: number, y: number): number { return x + y } It corresponds to the value of the above function
let myAdd2: (x: number, y: number) => number =
function(x: number, y: number): number {
return x + y
}

Optional and default parameters

TypeScript Every function parameter in the is required . This does not mean that it cannot be transmitted null or undefined As a parameter , Instead, the compiler checks whether the user has passed in a value for each parameter . The compiler also assumes that only these parameters will be passed into the function . In short , The number of parameters passed to a function must be consistent with the number of parameters expected by the function .

 

JavaScript in , Each parameter is optional , Can pass but not pass . When I didn't pass the reference , Its value is undefined. stay TypeScript We can use it next to the parameter name ? Realize the function of optional parameters . such as , We want to make lastName It's optional

 

stay TypeScript in , We can also provide a default value for the parameter when the user does not pass the parameter or the passed value is undefined when . They are called parameters with default initialization values . Let's modify the above example , hold firstName The default value of is set to "A".

function buildName(firstName: string='A', lastName?: string): string {
if (lastName) {
return firstName + '-' + lastName
} else {
return firstName
}
} // All in
console.log(buildName('C', 'D'))
// Pass in only last name
console.log(buildName('C'))
// Pass nothing on
console.log(buildName())

The remaining parameters

Necessary parameters , Default and optional parameters have one thing in common : They represent a parameter . Sometimes , You want to manipulate multiple parameters at the same time , Or you don't know how many parameters will be passed in . stay JavaScript in , You can use arguments To access all incoming parameters

 

stay TypeScript in , You can collect all the parameters into one variable :

The remaining parameters will be treated as an unlimited number of optional parameters . You can have none of them , There can also be any . The compiler creates an array of parameters , The name is you in the ellipsis ( ...) The name given later , You can use this array in the function body .

function info(x: string, ...args: string[]) {
console.log(x, args)
}
info('abc', 'c', 'b', 'a')

function overloading

function overloading : The function names are the same , And multiple functions with different formal parameters

stay JS in , Due to the characteristics of weak types and shape participation arguments can not match , There is no such thing as function overloading But in TS in , With other object-oriented languages ( Such as Java) There is this grammar

/*
function overloading : The function names are the same , And multiple functions with different formal parameters
demand : We have a add function , It can receive 2 individual string Type , You can also receive 2 individual number Add parameters of type
*/ // Overloaded function declaration
function add (x: string, y: string): string
function add (x: number, y: number): number // Define function implementation
function add(x: string | number, y: string | number): string | number {
// In implementation, we should pay attention to strictly judge whether the types of two parameters are equal , Instead of simply writing a x + y
if (typeof x === 'string' && typeof y === 'string') {
return x + y
} else if (typeof x === 'number' && typeof y === 'number') {
return x + y
}
} console.log(add(1, 2))
console.log(add('a', 'b'))

TypeScript(6) More articles on functions

  1. TypeScript Understanding of functions in ? And JavaScript Difference of function ?

    One . What is it? The function is JavaScript  The foundation of the application , Help us implement the abstraction layer . Simulation class . Information hiding and module stay TypeScript  in , Although classes are already supported . Namespace and module , But functions are still the main way to define behavior ,Type ...

  2. TypeScript Function( function )

    stay JavaScript in , Functions are the building blocks of any application . By function , You can build the abstraction layer . Imitation class . Information hiding and modularization . stay TypeScript in , Although classes and modularity already exist , But the function is still how to " It's about ...

  3. TypeScript introduction - function

    ▓▓▓▓▓▓ General introduction TypeScript by JavaScript Function adds extra functionality , Let's make it easier to use .TypeScript Functions in also include JavaScript Two of the most common functions in functio ...

  4. TypeScript And function

    https://m.runoob.com/manual/gitbook/TypeScript/_book/doc/handbook/Functions.html Define a type for a function Add types to functions : fu ...

  5. typescript - 3. function

    (1) Definition of function ## Function declaration method // function run():string{ // return 'run'; // } // Wrong writing , Return type error // function run():st ...

  6. 《 The front road 》- TypeScript( Two ) Function part

    Catalog One . Define function methods Two . Define function arguments 3、 ... and . Optional parameters Four . Default parameters 5、 ... and . Pass the remaining parameters 6、 ... and . function overloading 7、 ... and . Arrow function 8、 ... and . summary One . Define function methods stay es5 The methods of timing function in Name functions and function expressions ( Hide ...

  7. TypeScript Sketch - function

    /* Functions and javaScript It's not that different , It just adds additional functions , Make the function have More powerful and easier to use */ // Now support function parameter specifying type , In the previous blog post, you should have seen // You can also specify the... Of the function ...

  8. typescript Function of

    1: Default parameters ( The passed in value overrides the default parameter , It's OK not to transfer values ) function getinfo(name:string,age:number=20):string{ return `${name}---${age ...

  9. TypeScript A function of

    1. Function declaration And javascript equally ,ts There are also two types of function declarations for : Function declaration , Function expression 1) Function declaration : function fn(age:number):string{ return `age is ...

  10. TypeScript The local variables in the function “ export ” Methods

    The first is in the module a.js Declare an exportable (export) Data structure of , for example : export class ModelInfo{ id: string; name:string; } The second is in the module b Is declared to be exportable ...

Random recommendation

  1. ajax Submit form Forms

    1. ajax Submit form Forms and different form The main difference between forms submission is ,ajax Submit forms are submitted asynchronously , The normal form is submitted synchronously . 2. from View part <form id="loginF ...

  2. C++ Class knowledge points

    1. member function definitions are processed after the compiler processes all of the declarations in ...

  3. Ruby Summary of learning resources

    from:http://segmentfault.com/a/1190000000362058 Ruby Language Try Ruby: There's no need to install... On your system .Ruby, You can experience it immediately through the browser Ruby ...

  4. turn :Java Annotation Detailed explanation

    Reprinted from :http://william750214.javaeye.com/blog/298104 The role of metadata If you want to classify the role of metadata , There is no clear definition yet , But we can depend on what it does , roughly ...

  5. [Design Pattern] Adapter Pattern A simple case

    Adapter Pattern, Adapter mode , Used to connect two incompatible interfaces , Design patterns that belong to the structural class . Or called , Converter mode . The following is a simple example of the converter pattern . Suppose there is already AudioPlayer Specially play m ...

  6. c++ polymorphism --- Virtual functions

    The difference between virtual function and pure virtual function : 1. Classes with virtual functions can declare objects , But classes with pure virtual functions cannot declare objects ( Only one pointer can be declared , And you can't allocate memory to it ), And call this class an abstract class characteristic : 1. Virtual functions are the basis of dynamic binding . 2. ...

  7. Stuck on &quot;Authenticating with iTunes Store&quot;

    https://forums.developer.apple.com/thread/76803 Try this, it fixed it for me. Open Terminal and run: ...

  8. JS Quick start notes

    1.JavaScript Don't distinguish between integers and floating-point numbers , Unified use Number Express . NaN; // NaN Express Not a Number, When the result cannot be calculated, use NaN Express Infinity; // Infinity It means nothing ...

  9. Python Algorithm : deduction 、 Recursion and Convention

    Python Algorithm : deduction . Recursion and Convention notes : In this section, I give the Chinese translation of the following three important words :Induction( deduction ).Recursion( recursive ) and Reduction( Statute ) This section mainly introduces the three cores of algorithm design ...

  10. linux iscsi Mount and unload

    iscsiadm -m discovery -t sendtargets -p 192.168.4.245:3260 # scanning ISCSI Target List all LUN iscsiadm -m node ...