Typescript 函数类型

本文介绍了TypeScript中函数的定义,包括有返回值和无返回值的函数、箭头函数的使用,以及函数参数的默认值和可选参数设定。此外,还讨论了参数为对象时的接口定义,函数中的`this`类型约束,以及函数重载的概念和应用示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

定义函数的参数与返回值类型

// 有返回值
function showInfo(name: string, age: number): string {
  return `${name}: ${age}`
}

// 没有返回值
function showLog(name: string): void {
  console.log(name)
}

箭头函数的定义

const showInfo = (name: string): string => {
  return name
}

const showLog = (name: string): void => {
  console.log(name)
}

函数的默认值 与 可选参数

// 默认值
const showName = (name: string = '张三'): void => {
  console.log(name)
}

// 可选参数
const showLog = (name: string = '张三', age?: number) => {
  console.log(`${name}: ${age}`)
}

参数是对象如何定义

  • 集合 interface 定义
interface Info {
  name: string
  age?: number
}

const showInfo = (info: Info): string => {
  return `${info.name}: ${info.age}`
}

console.log(showInfo({name: '张三', age: 19}))

函数 this 类型 (在对象中的使用)

  • ts 中 可以定义 this 的类型 在 js 中是不能这么使用的了, 必须是方法的第一个参数
interface Info {
  name: string;
  show: (this: Info) => void;
}

const info: Info = {
  name: '张三',
  show(this: Info) {
    console.log(this.name)
  },
}
info.show()

函数重载 (根据参数的不同实现不同的功能)

let info: number[] = [1, 2, 3, 4, 5 ]

function sumInfo(add: number[]): number[]  // 若参数是一个number类型的数组, 将做添加操作
function sumInfo(id: number): number[]  // 若参数是一个number参数, 将返回查找到的数字
function sumInfo(): number[]  // 若是没有传递参数,将返回所有数据

function sumInfo(id?: number[] | number): number[] {
  if (!id) {
    return info
  }
  if (id && Array.isArray(id)) {
    info = [...info, ...id]
    return info
  }
  if (id && typeof id === 'number') {
    return info.filter((it: number) => it === id)
  }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值