ts中的函数

96 阅读1分钟

函数

  1. 关键字function
function say() {
    console.log('say function')
}
say()

  1. 有参数的函数

    function say(str:string) {
        console.log('say '+ str)
    }
    say('hello')
    
    
    
  2. 无返回值的函数

    function say(str: string): void {
        console.log('say ' + str)
    }
    
    say('hello')
    
    
    
  3. 有返回值的函数

    function say(str: string): string {
        return str
    }
    
    let hello = say('hello')
    console.log(hello)
    
    // hello
    
    
  4. 可选参数的函数

    function say(str?: string): void {
        console.log(str)
    }
    
    say()
    //undefined
    say('hello')
    //hello
    
  5. 函数参数的默认值

    function say(str: string = 'hello'): void {
        console.log(str)
    }
    
    
    say()
    //hello
    say('hello !!!')
    //hello !!!
    

有多个参数,可选参数放在最后

function say(str: string = 'hello', str1?: string): void {
    console.log(str)
}

say()
//hello
say('hello !!!')
//hello !!!