function
This is the 12th day of my participation in the August More Text Challenge. For details, see:August is more challenging
As with JavaScript, TypeScript functions can create named and anonymous functions.
// Named function
function add(x, y) {
return x + y;
}
// Anonymous function
let myAdd = function(x, y) { return x + y; };
Copy the code
Function types
function add(x: number, y: number) :number {
return x + y;
}
let myAdd = function(x: number, y: number) :number { return x + y; };
Copy the code
Because TypeScript automatically inferences the return value type from the return statement, we often omit the return value type of a function
A function type consists of two parts: the parameter type and the return value type
let myAdd: (x:number, y:number) = > number =
function(x: number, y: number) :number { return x + y; };
Copy the code
Inference type
If you have a type on one side of the equation, the TypeScript compiler still recognizes the type correctly
This is called “categorizing by context” and is a form of type inference. It helps us better specify types for programs.
// myAdd has the full function type
let myAdd = function(x: number, y: number) :number { return x + y; };
// The parameters `x` and `y` have the type number
let myAdd: (baseValue: number, increment: number) = > number =
function(x, y) { return x + y; };
Copy the code
This parameter is optional and default
TypeScript assumes by default that every argument to a function is required
function buildName(firstName: string, lastName: string) {
return firstName + "" + lastName;
}
let result1 = buildName("Bob"); // error, too few parameters
let result2 = buildName("Bob"."Adams"."Sr."); // error, too many parameters
let result3 = buildName("Bob"."Adams"); // ah, just right
Copy the code
In JavaScript, each parameter is optional and can be passed or not. When no argument is passed, its value is undefined. In TypeScript we can use it next to the parameter name, right? Implement the function of optional parameters
Optional arguments must be followed by required arguments
function buildName(firstName: string, lastName? :string) {
if (lastName)
return firstName + "" + lastName;
else
return firstName;
}
let result1 = buildName("Bob"); // works correctly now
let result2 = buildName("Bob"."Adams"."Sr."); // error, too many parameters
let result3 = buildName("Bob"."Adams"); // ah, just right
Copy the code
In TypeScript, we can also provide a default value for an argument when the user does not pass it or when the value passed is undefined
function buildName(firstName: string, lastName = "Smith") {
return firstName + "" + lastName;
}
let result1 = buildName("Bob"); // works correctly now, returns "Bob Smith"
let result2 = buildName("Bob".undefined); // still works, also returns "Bob Smith"
let result3 = buildName("Bob"."Adams"."Sr."); // error, too many parameters
let result4 = buildName("Bob"."Adams"); // ah, just right
Copy the code
Arguments with default initialization after all required arguments are optional and, like optional arguments, can be omitted when the function is called. That is, the optional parameter shares the parameter type with the default parameter at the end
function buildName(firstName: string, lastName? :string) {
// ...
}
function buildName(firstName: string, lastName = "Smith") {
// ...
}
FirstName: string, lastName? : string) => string
Copy the code
Unlike normal optional parameters, parameters with default values do not need to be placed after the required parameters. If a parameter with a default value appears before a required parameter, the user must explicitly pass in undefined to get the default value
function buildName(firstName = "Will", lastName: string) {
return firstName + "" + lastName;
}
let result1 = buildName("Bob"); // error, too few parameters
let result2 = buildName("Bob"."Adams"."Sr."); // error, too many parameters
let result3 = buildName("Bob"."Adams"); // okay and returns "Bob Adams"
let result4 = buildName(undefined."Adams"); // okay and returns "Will Adams"
Copy the code
The remaining parameters
When you want to manipulate more than one argument at a time, or you don’t know how many arguments will be passed in, you can use the remaining arguments
function buildName(firstName: string. restOfName:string[]) {
return firstName + "" + restOfName.join("");
}
let employeeName = buildName("Joseph"."Samuel"."Lucas"."MacKinzie");
Copy the code
The remaining arguments are treated as an unlimited number of optional arguments. I could have none of them, or I could have any of them. The compiler creates an array of parameters whose names are your ellipses (…). You can use this array in the body of the function with the name given later.
Literal type
A literal is a more specific subtype of a collective type
There are currently three sets of literal types available in TypeScript: strings, numbers, and Booleans. By using literal types, you can specify the definite value that a string, number, or Boolean value must contain.
// Name is of type 'Klaus', not string
let name = 'Klaus'
name = 'Alex' // error
Copy the code
Literal types can be combined with actual string values through federation, type guards, and type aliases. With these properties, we can take a string and make it behave like an enum.
type Easing = "ease-in" | "ease-out" | "ease-in-out";
class UIElement {
animate(dx: number, dy: number, easing: Easing) {
if (easing === "ease-in") {
// ...
} else if (easing === "ease-out") {}else if (easing === "ease-in-out") {}else {
// It's possible that someone could reach this
// by ignoring your types though.}}}let button = new UIElement();
button.animate(0.0."ease-in");
button.animate(0.0."uneasy");
// Error: Argument of type '"uneasy"' is not assignable to parameter of type 'Easing'.
Copy the code
The numeric literal type
Numeric literal types are often used to describe configuration values
interface MapConfig {
lng: number;
lat: number;
tileSize: 8 | 16 | 32;
}
setupMap({ lng: -73.935242.lat: 40.73061.tileSize: 16 });
Copy the code