One, js three definition function ts implementation
Functions in TS are mostly the same as those in JS, except that TS adds a type declaration between and after the function (parameter)
// JavaScript defines the method of the function
// Name the function
function say1(name) {
console.log(name);
}
// Anonymous function
let say2 = function (name) {
console.log(name);
}
// Arrow function
let say3 = (name) = > {
console.log(name);
}
Copy the code
// typescript defines methods for functions
// Name the function
function say1(name:string) :void {
console.log(name);
}
// Anonymous function
let say2 = function (name:string) :void {
console.log(name);
}
// Arrow function
let say3 = (name:string) :void= >{
console.log(name);
}
Copy the code
Two, ts function declaration and implementation of the separation of writing
(1) Use type to declare a function
// Declare a function using type
type AddFun = (a:number, b:number) = >number;
Copy the code
// Implement this function according to the declaration
// The function's parameters and return values do not need to write the type declaration, because ts can infer the type from the function declaration
let add:AddFun = function (x, y) {
return x + y;
};
let res = add(30.20);
console.log(res);
Copy the code
(2) Use interface to declare function
// Use interface to declare a function
interface AddFun {
(a:number.b:number) :number
}
Copy the code
let add:AddFun = function (x, y) {
return x + y;
};
let res = add(30.20);
console.log(res);
Copy the code
Three, JS function parameters of the three uses of TS implementation
(1) Optional parameters
// Define a function that can add two or three numbers
function add(x:number, y:number, z? :number) :number {
return x + y + (z ? z : 0);
}
let res = add(10.20);
let res = add(10.20.30);
Copy the code
Matters needing attention:
The optional parameters can be one or more
function add(x:number, y? :number, z? :number):number {
Optional parameters can only be followed by optional parameters
function add(x:number, y? :number, z:number):number
(2) Default parameters
function add(x:number, y:number=10) :number {
return x + y;
}
let res = add(10);
let res = add(10.30);
Copy the code
(3) Remaining parameters
function add(x:number. ags:number[]) {
console.log(x);
console.log(ags);
}
add(10.20.30.40.50)
Copy the code
Ts Introduction Notes Directory:
TS Introduction Note 1 – Type declarations for TS
TS Introduction Note 2 – TS interface further details
TS Introduction Note 3 — Function declarations in TS
TS Introduction Note 4 — Type Assertion for TS (Interpreted type conversions)
TS Introduction Note 5 – TS generics
TS Introduction Note 6 — Declaration files, modules, namespaces in TS
Record knowledge, transfer happiness ~
If my summary is helpful to you, please give me a thumbs up. Your encouragement is a great motivation for me to keep recording
If there are any errors in this article, please feel free to point them out in the comments