当前位置:网站首页>TS quick start - functions
TS quick start - functions
2022-07-05 00:14:00 【Warmth key】
stay TS in , Although classes are already supported , Namespace and module , But functions are still the main place to define behavior
TS Most of the functions in are related to JS identical , The difference is ts Type declaration will be added to the return value and parameters of the function
stay TS in , Functions are still the most basic 、 One of the most important concepts
Function type definition
The definition of function type includes Parameters and Return value Type definition of
1. Directly define function types
function sayMyself(name: string, age: number): string {
return ` I am a ${
name}, I this year ${
age} year `;
}
const sayMyself = (name: string, age: number) => {
return ` I am a ${
name}, I this year ${
age} year `;
}
console.log(sayMyself(' Warmth key', 23)); // I am warm key, I this year 23 year
function printMsg(warn: string): void {
console.warn(' Warning message ', warn);
}
const printMsg = (warn: string): void => {
console.warn(' Warning message ', warn);
}
printMsg(' Warning warning 123'); // Warning message Warning warning 123
If the type of the parameter is omitted here ,TypeScript The default parameter is any type ;
If you omit the type of the return value
If the function has no return value , that TypeScript The default function return value is void type ;
If the function has a return value , that TypeScript The return type will be inferred according to the defined logic .
2. type Define function types
/* First use of type Declare a function */
type Submit = (user: string, props: object) => string;
/* Then implement the function according to the declaration of the function */
const submitHandle: Submit = (user, props) => {
return ` Submit successfully , ${
user}`
// return 123 // Returning a number will report an error , The error message is as follows
// You can't type “(user: string, props: object) => number” Assign to type “Submit”. You can't type “number” Assign to type “string”.
}
submitHandle(' Warmth key', {
age: 22 });
// submitHandle(123, { age: 22 }); // error type “number” Argument to cannot be assigned to type “string” Parameters of .
3. interface Define function types
Function types can be clearly defined using interfaces
interface AddInt {
(x: number, y: number): number;
}
const add: AddInt = (a, b) => {
return a + b
}
// You can't type “(a: number, b: number) => string” Assign to type “AddInt”.
// You can't type “string” Assign to type “number”.
// const add: AddInt = (a: number, b: number) => {
// return 'wwww'
// }
Function parameter definition
1. Optional parameters
The definition of optional parameters only needs to add a ?
const add = (x: number, y: number, z?: number): number => {
return x + y + ( z ? z : 0 )
}
console.log(add(1 , 2)); // 3
console.log(add(1 , 2, 3)); // 6
The optional parameters can be one or more
const add = (x: number, y?: number, z?: number): number => {
return x + ( y ? y : 0 ) + ( z ? z : 0 )
}
console.log(add(1 , 2)); // 3
Once optional parameters appear, they can only be followed by optional parameters
const add = (x: number, y?: number, z: number): number => {
// error Required parameters cannot be after optional parameters
return x + ( y ? y : 0 ) + ( z ? z : 0 )
}
2. Default parameters
The default parameter only needs to be assigned an initial value
const add = (x, y = 20) => {
console.log(x + y);
}
add(10); // 30
add(10, 70); // 80
When a default parameter is specified for a parameter ,TS Will recognize the default value and infer the type of this parameter . When the function is called , If the actual parameter type is inconsistent with the default parameter type, an error will be reported
const add = (x, y = 20) => {
console.log(x + y);
}
add(10); // 30
add(10, '70'); // error type “string” Argument to cannot be assigned to type “number” Parameters of .
Of course, you can also explicitly set the type of default parameters
const add = (x: number, y: number = 20): void => {
console.log(x + y);
}
add(10); // 30
add(10, 60); // 70
3. The remaining parameters
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 will create an array of parameters , The name is in Ellipsis ... The name given later , You can use this array in the function body .
const add = (...args: number[] ) => {
const res = args.reduce((pre, cur) => {
return pre + cur
})
console.log(res);
}
add(1, 2, 3); // 6
add(10, 20, 30, 50, 90); // 200
function overloading
The function names are the same , And multiple functions with different formal parameters
So called function overload is the same function , Depending on the parameters passed , There will be different forms of expression .
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 , This syntax exists with other object-oriented languages
// demand : Define 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 | undefined {
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)); // 3
console.log(add(' Warmth ', 'key')); // Warmth key
console.log(add(1, 'key')); // The error information is as follows
// The first 1 Heavy haul ( common 2 individual ),“(x: string, y: string): string”, The following error occurred .
// type “number” Argument to cannot be assigned to type “string” Parameters of .
// The first 2 Heavy haul ( common 2 individual ),“(x: number, y: number): number”, The following error occurred .
// type “string” Argument to cannot be assigned to type “number” Parameters of .
Be careful : Function overloading can only use function To define , Out of commission interfacetype To define .
边栏推荐
- 【报错】 “TypeError: Cannot read properties of undefined (reading ‘split‘)“
- In June, the list of winners of "Moli original author program" was announced! Invite you to talk about the domestic database
- "Xiaodeng" domain password policy enhancer in operation and maintenance
- P4408 [noi2003] truant children (tree diameter)
- 他做国外LEAD,用了一年时间,把所有房贷都还清了
- OpenHarmony资源管理详解
- Nine Qi single chip microcomputer ny8b062d single key control four LED States
- 2022.07.03(LC_6111_统计放置房子的方式数)
- 使用快解析搭建自己的minecraft服务器
- Five papers recommended for the new development of convolutional neural network in deep learning
猜你喜欢

What did I pay for it transfer to testing post from confusion to firmness?
![[IELTS reading] Wang Xiwei reading P3 (heading)](/img/19/40564f2afc18fe3e34f218b7b44681.png)
[IELTS reading] Wang Xiwei reading P3 (heading)

快解析内网穿透帮助企业快速实现协同办公

Hisilicon 3559 universal platform construction: YUV422 pit stepping record

图解网络:什么是网关负载均衡协议GLBP?

微服务(Microservice)那点事儿

Data on the number of functional divisions of national wetland parks in Qinghai Province, data on the distribution of wetlands and marshes across the country, and natural reserves in provinces, cities

Microservice
![[论文阅读] TUN-Det: A Novel Network for Thyroid Ultrasound Nodule Detection](/img/25/e2366cabf00e55664d16455a6049e0.png)
[论文阅读] TUN-Det: A Novel Network for Thyroid Ultrasound Nodule Detection

Jar batch management gadget
随机推荐
企业公司项目开发好一部分基础功能,重要的事保存到线上第一a
Business implementation - the log is written to the same row of data
Significance of acrel EMS integrated energy efficiency platform in campus construction
Using fast parsing intranet penetration to realize zero cost self built website
Go pit - no required module provides Package: go. Mod file not found in current directory or any parent
Jar batch management gadget
The input of uniapp is invalid except for numbers
基本放大电路的学习
如何将自己的代码作品快速存证,已更好的保护自己劳动成果
P4281 [ahoi2008] emergency assembly / gathering (LCA)
Réseau graphique: Qu'est - ce que le Protocole d'équilibrage de charge de passerelle glbp?
P3304 [SDOI2013]直径(树的直径)
P4408 [noi2003] truant children (tree diameter)
Hisilicon 3559 universal platform construction: YUV422 pit stepping record
The waterfall flow layout demo2 (method 2) used by the uniapp wechat applet (copy and paste can be used without other processing)
如何避免电弧产生?—— AAFD故障电弧探测器为您解决
Acwing164. Accessibility Statistics (topological sorting +bitset)
Date time type and format in MySQL
Skills in analyzing the trend chart of London Silver
GDB common commands