TypeScript-函数

文章介绍了如何在TypeScript中定义和使用函数类型,包括使用类型别名定义GreetFunction,调用签名定义DescribableFunction,以及构造签名在类Ctor中的应用。示例展示了如何将这些类型应用于实际函数和构造函数,并通过fn1和Ctor展示了类型系统的灵活性。

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

1、函数类型表达式

// 使用类型别名
type GreetFunction = (a:string)=>void
function greeter(fn:GreetFunction){
  fn('hello world')
}

function printToConsole(s:string){
  console.log(s);
  
}
greeter(printToConsole)

2、调用签名

type DescribableFunction = {
  description:string,
  (someAag:number):boolean
}
function doSomething(fn:DescribableFunction){
  console.log(fn.description+' returned '+fn(6));
  
}
function fn1(n:number){
  console.log(n);
  return true
}
fn1.description = 'hello'
doSomething(fn1)

3、构造签名

class Ctor{
  s:string
  constructor(s:string){
    this.s = s
  }
}

type SomeConstructor = {
  new (s:string):Ctor
}

function fn(ctor:SomeConstructor){
  return new ctor('hello')
}

const f = fn(Ctor)
console.log(f.s);

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值