当前位置:网站首页>TypeScript函数详解
TypeScript函数详解
2022-07-02 04:36:00 【wendyTan10】
在JavaScript开发中,函数是可作为参数,也可以作为返回值进行传递;那在使用函数的过程中,函数也会具备自己的类型;我们可以编写函数类型的表达式(
Function Type Expressions),来表示函数类型; 类型的定义
函数类型的定义:(num1: number, num2: number) => void;
-接收两个参数的函数:num1和num2;number类型
-void表示没有返回值;
// type 定义函数的类型
type AddFnType = (num1: number, num2: number) => number
const add: AddFnType = (a1: number, a2: number) => {
return a1 + a2
}
-并且num1和num2在typescript中是不可省略;
可指定某个参数是可选值:
// 可选类型是必须写在必选类型的后面的
// y -> undefined | number
function foo(x: number, y?: number) {
console.log(x, y);
}
参数的默认值
// 必传参数 - 有默认值的参数 - 可选参数
function foo(y: number, x: number = 20) {
console.log(x, y)
}
this类型的推倒
可推导的this类型
在javascript中有关this的使用,是比较难以理解和把握的知识点;因为this在不同的情况下绑定不痛的值,所有导致对于它的类型难以把握;
我们来翻看一个例子,下面这段代码中会报错;是因为typescript检测到不安全
function sayHell() {
console.log(this.name);
}
const info = {
name: "why",
sayHell: sayHell
};
info.sayHell();
TypeScript会要求我们明确的指定this的类型:
type NameType = {
name: string
}
function sayHell(this: NameType) {
console.log(this.name);
}
type ThisType = {
name: string };
function eating(this: ThisType, message: string) {
console.log(this.name + " eating", message);
}
const info = {
name: "why",
eating: eating,
};
// 隐式绑定
info.eating("哈哈哈");
// 显示绑定
eating.call({
name: "kobe"}, "呵呵呵")
eating.apply({
name: "james"}, ["嘿嘿嘿"])
函数的重载
在TypeScript中,如果我们编写了一个add函数,希望可以对字符串和数字类型进行相加,应该如何编写呢? 我们可能第一反应是想到是使用联合类型去编写;
function add(a1: number | string, a2: number | string) {
return a1 + a2;
}
但是其实是错误的:
在TypeScript中,我们可以去编写不同的重载签名(overload signatures)来表示函数可不同的方式进行
调用;一般编写两个或者以上的重载签名,再去编写一个通用的函数以及实现;
// 函数的重载: 函数的名称相同, 但是参数不同的几个函数, 就是函数的重载
function add(num1: number, num2: number): number; // 没函数体
function add(num1: string, num2: string): string;
function add(num1: any, num2: any): any {
if (typeof num1 === 'string' && typeof num2 === 'string') {
return num1.length + num2.length
}
return num1 + num2
}
联合类型和重载
当我们定义一个联合类型的函数,有俩种方案可实现:
- 方式一: 联合类型
function getLength(args: string | any[]) { return args.length } console.log(getLength("abc")) console.log(getLength([123, 321, 123])) - 方式二: 函数的重载
function getLength(args: string): number; function getLength(args: any[]): number; function getLength(args: any): number { return args.length } console.log(getLength("abc")) console.log(getLength([123, 321, 123]))
在可能的情况下,尽量选择使用联合类型来实现;更加的简洁;
边栏推荐
- powershell_ View PowerShell function source code (environment variable / alias) / take function as parameter
- LCM of Spreadtrum platform rotates 180 °
- IDEA xml中sql没提示,且方言设置没用。
- Wechat applet calculates the distance between the two places
- [graduation season · advanced technology Er] young people have dreams, why are they afraid of hesitation
- 6月书讯 | 9本新书上市,阵容强大,闭眼入!
- Pytorch-Yolov5從0運行Bug解决:
- Www 2022 | rethinking the knowledge map completion of graph convolution network
- Pytorch---使用Pytorch实现U-Net进行语义分割
- DC-1靶场搭建及渗透实战详细过程(DC靶场系列)
猜你喜欢

Www2022 | know your way back: self training method of graph neural network under distribution and migration

Research on the security of ognl and El expressions and memory horse

Mysql database learning

Realize the function of data uploading

Spring moves are coming. Watch the gods fight

云服务器的安全设置常识

Thinkphp内核工单系统源码商业开源版 多用户+多客服+短信+邮件通知

Spring recruitment of Internet enterprises: Kwai meituan has expanded the most, and the annual salary of technical posts is up to nearly 400000

Gin framework learning code

UNET deployment based on deepstream
随机推荐
Pytoch --- use pytoch for image positioning
One click generation and conversion of markdown directory to word format
Deeply understand the concepts of synchronization and asynchrony, blocking and non blocking, parallel and serial
Wechat applet pull-down loading more waterfall flow loading
Learn AI safety monitoring project from zero [attach detailed code]
Yyds dry goods inventory kubernetes introduction foundation pod concept and related operations
Pytoch yolov5 runs bug solution from 0:
Landing guide for "prohibit using select * as query field list"
unable to execute xxx. SH: operation not permitted
Alibaba cloud polkit pkexec local rights lifting vulnerability
Typescript practice for SAP ui5
Today's plan: February 15, 2022
GeoTrust ov multi domain SSL certificate is 2100 yuan a year. How many domain names does it contain?
CY7C68013A之keil编译代码
Leetcode merge sort linked list
What is 5g industrial wireless gateway? What functions can 5g industrial wireless gateway achieve?
Homework of the 16th week
Yolov5 network modification tutorial (modify the backbone to efficientnet, mobilenet3, regnet, etc.)
Binary tree problem solving (2)
Pytorch yolov5 exécute la résolution de bogues à partir de 0: