赞
踩
函数:参数列表里面的每个参数都需要名称和类型,
函数本身也可以添加返回值类型,TypeScript能够根据返回语句自动推断出返回值类型,因此我们通常省略它
- function add(x: number, y: number): number {
- return x + y;
- }
- add(1, 2); //函数传参少了,多了都不行,参数定死了
-
- function fn(): number {
- return 100;
- }
-
- function fm(arg1: number, arg2: any[]): [number, any[]] {//[number, any[]]返回值类型是一个元组
- return [arg1 * arg1, [123, "abc", arg2]];
- }
- console.log(fm(100, ["hello world"]));//[ 10000, [ 123, 'abc', [ 'hello world' ] ] ]
-
-
- interface Person {
- age: number,
- color: string
- }
- function f(age: number, color: string): Person[] { //Person[] :Person接口类型的数组
- return [{ age, color }]
- }
- f(100, "red");
- let arr = [function add(x: number, y: number): number { return x + y; }];
-
- (function add(x: number, y: number): number {
- return x + y;
- })(10, 10);
-
- let myAdd = function (x: number, y: number): number { return x + y; };
可选参数一般放在必填参数后面,?表示可选参数
- interface Params {
- params: object
- }
- function Myaxiosget(arg1: string, arg2?: Params) {// ?表示可选参数
- console.log(arg1, arg2);
- }
-
- Myaxiosget("http://xxx", { params: { id: 1 } })//http://xxx { params: { id: 1 } }
- Myaxiosget("http://xxx")//http://xxx undefined
在类型后加 “=值”
- // 默认参数
- function fx(arg1: number, arg2: string = "test") { //="xxxxx":表示默认参数
- console.log(arg1, arg2);
- }
- fx(123)//123 test
- fx(123, "world")//123 world
- // undefined可以不传值的时候占位
- function fx2(arg1: number, arg2?: string, arg3?: string) {
- console.log(arg1, arg2, arg3);
- }
- fx2(123, undefined, "world")//123 undefined world
-
- function fx3(arg1: number = 100, arg2: string) {
- console.log(arg1, arg2);
- }
- fx3(undefined, "world")//100 world
...rest表示,(...rest:只能放最后面,是个数组)
- function ff(arg1: any, arg2: any, ...rest): void {
- console.log(arg1, arg2, rest);
- }
- ff(10, "hello");//10 hello []
- ff(10, "hello", 10, 200, 300);//10 hello [ 10, 200, 300 ]
(参数1:类型,参数2:类型)=>返回值类型
- let aa = 100;
- let f1: (number) => number;//来描述f1的返回类型是number
- f1 = function (arg1: number): number {
- return arg1 + 100;
- };
- function f2(arg1: number): number {
- return 200;
- }
- f1 = f2;
- f1(90);
- let f1: (number) => number;//函数类型描述
- let f3 = (arg1: number): number => arg1;//箭头函数 ①有等号,②返回值=> arg1是一个变量
- interface MyTool {
- (number): number //: number是指函数的返回值类型
- }
- let pp: MyTool;
- pp = (arg: number): number => { //箭头函数
- return 200;
- }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。