Skip to content
ts
// 函数声明

function getA(a:string, b:string):void {
  console.log('A')
}

function getB(a:string, b:string):string {
  return 'B'
}

// 函数表达式

const getC = function (a:string, b:string):void {
  console.log('C')
}

const getD = function (a:string, b:string):string {
  return 'D'
}

const getE:(a:string, b:string) => string = function (a, b) {
  return 'E'
}

type MyFunction = (a:string, b:string) => string

const getF:MyFunction = function (a, b) {
  return 'F'
}

// getF.f = 'F'

// 函数类型 还可以用对象来表示

const getG:{
  (a:string, b:string): string,
  g:string
} = function (a, b) {
  return 'G'
}

getG.g = 'G'

// 箭头函数

const getH = (a:string, b:string):string => 'H'
ts
// 函数实际参数可以比类型定义的少
type GetA = (a:string, b:string) => string

const getA:GetA = a => a

// 如果要显式的声明某参数是可选的。可以用?表示参数是可选的,可以是string或者undefined
type GetB = (a:string, b?:string) => string

const getB:GetB = a => a

// 但可选参数必须位于末尾。A required parameter cannot follow an optional parameter.
// type GetC = (a?:string, b?:string, c:string) => string

// 如果真需要上述场景的话,可以显式将参数声明为undefined
type GetD = (a:string|undefined, b:string|undefined, c:string) => string