【typescript 03】函数的定义

old

1. 声明函数

  • function funcA() {
        console.log('AAA');
    }

2. 匿名函数

  • let funcB = () => {
        console.log('BBB');
    }

ts:

多出了的额外工作:输入(需要制定类型)输出(需要制定类型)

1. 声明函数

  • function tsFuncGirl(name: string, age: number): void {
        const person = {
            name,
            age,
            sex: 'girl'
        }
        console.log(JSON.stringify(person));
    }
    
    tsFuncBoy('kjf', 24);

2. 匿名函数

  • let tsFuncBoy = (name: string, age: number): string => {
        const person = {
            name,
            age,
            sex: 'boy'
        }
        return JSON.stringify(person);
    }
    
    console.log(tsFuncBoy('kjf', 24));

可选参数(可传可不传的参数,必须是最后的若干个参数,即不能 function func(a:number, b?: number, c: number) 

  • let tsFuncBoy = (name: string, age?: number): string => {
        const person = {
            name,
            age: age || '保密',
            sex: 'boy'
        }
        return JSON.stringify(person);
    }
    
    console.log(tsFuncBoy('kjf'));

默认参数(es5 无法设置默认参数,ts 和 es6 都可以设置默认参数)

  • let tsFuncPerson = (name: string, age?: number, sex: string = 'boy'): string => {
        const person = {
            name,
            age: age || '保密',
            sex
        }
        return JSON.stringify(person);
    }
    
    console.log(tsFuncPerson('god', 18, 'girl'));

剩余参数

3

3

3

3

posted @ 2020-08-02 23:45  耶梦加德  阅读(167)  评论(0编辑  收藏  举报