我们上一篇内容简单的介绍了判断语句以及循环语句,今天我们一起来学习一下TS中的函数,除此之外我还会再介绍两个和函数相关的配置。
函数通常按照有没有返回值,可以分为两种,一种是要指定返回值类型的,另一种是没有返回值的,通常用void来表示这个函数没有返回值。
我们一起看一下下面这段代码
function calculator(num1: number, num2: number, operator: string): number {
let result = 0;
if (operator == "+") {
result = num1 + num2;
} else if (operator == "-") {
result = num1 - num2;
} else if (operator == "*") {
result = num1 * num2;
} else if (operator == "/") {
result = num1 / num2;
}
return result;
}
这里calculator
就是我们自定义的函数名,它接收三个参数(通常我们称它们为“形参”),并且指定了数据类型。
我们在函数内部实现了根据运算符的不同,对输入的两个数据进行不同的计算,并将它的结果返回。
因此我们可以看到函数的返回值类型被我们指定为了number。
定义好了函数,该如何使用呢?我们可以通过如下的方式进行调用:
const my_result = calculator(1, 2, "+");
这里我们调用了这个方法,同时传入了三个参数(我们通常称它们为“实参”)。
我们有的时候还可以采用匿名函数的写法,即function后面不写函数名。
let calculator = function (
num1: number,
num2: number,
operator: string
): number {
let result = 0;
if (operator == "+") {
result = num1 + num2;
} else if (operator == "-") {
result = num1 - num2;
} else if (operator == "*") {
result = num1 * num2;
} else if (operator == "/") {
result = num1 / num2;
}
return result;
};
我们可以看到,function关键字后面并没有跟函数名,而是将整个函数赋值给了一个变量。它除了写法不同之外和普通的函数在使用上没有什么太大的差别。
const my_result = calculator(2, 2, "*");
console.log(my_result);
匿名函数我们省略了函数名,我们甚至还可以省略function这个关键字,而是使用=>这个箭头符号来代替。具体写法如下
let calculator = (num1: number, num2: number, operator: string): number => {
let result = 0;
if (operator == "+") {
result = num1 + num2;
} else if (operator == "-") {
result = num1 - num2;
} else if (operator == "*") {
result = num1 * num2;
} else if (operator == "/") {
result = num1 / num2;
}
return result;
};
你可以观察一下它的变化,删掉了function,并在返回值类型后面加了箭头符号(=>)这个符号是由等号和大于号组成的。它的用法也没有什么特殊的。
const my_result = calculator(9, 2, "/");
console.log(my_result);
我们前面配置了一个基础的编译配置项,如下
{
"compilerOptions": {
"target": "es2016",
"module": "commonjs",
"rootDir": "./src",
"outDir": "./dist",
"removeComments": true,
"noEmitOnError": true,
"esModuleInterop": true,
"forceConsistentCasingInFileNames": true,
"strict": true,
"skipLibCheck": true
}
}
现在我们接触到了函数这个用法,当我一个函数写的特别长时,传入的参数变多时,我们希望能让它实现以下两个功能:
为了实现这样的功能,我将下面这两个配置添加到原来的配置中
"noUnusedParameters": true,
"noUnusedLocals": true
修改后的配置文件
{
"compilerOptions": {
"target": "es2016",
"module": "commonjs",
"rootDir": "./src",
"outDir": "./dist",
"removeComments": true,
"noEmitOnError": true,
"esModuleInterop": true,
"forceConsistentCasingInFileNames": true,
"strict": true,
"skipLibCheck": true,
"noUnusedParameters": true,
"noUnusedLocals": true
}
}
这时我们在刚刚创建的函数里面加入一个参数
我们添加一个一个name_str
的参数,可以看到VSCode是有提示的,并且控制台也有报错。
我们再尝试在函数内部加入一个多余的变量。
可以看到它也有提示,这样当我们写大量函数时就可以避免出现多余的形成或者多余的局部变量了。
今天我们一起学习了如何在TS中编写函数,并修改了一下编译配置文件。希望对你能有所帮助。
今天的内容就是这些了,我是Tango,一个热爱分享技术的程序猿我们下期见。
我正在参与2024腾讯技术创作特训营第五期有奖征文,快来和我瓜分大奖!
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。