Detailed TypeScript function

One, the labeling of the function

The label of a function contains

  • parameter
  • return value
function fn(a: string): string {};
let fn: (a: string) => string = function(a) {};

type callback = (a: string): string;
interface ICallBack {
  (a: string): string;
}

let fn: callback = function(a) {};
let fn: ICallBack = function(a) {};

Two, optional parameters and default parameters

【1】Optional parameters

? Mark that the parameter is optional by adding it after the parameter name 

let div = document.querySelector('div');
function css(el: HTMLElement, attr: string, val?: any) {

}
// 设置
div && css( div, 'width', '100px' );
// 获取
div && css( div, 'width' );

[2] Default parameters

We can also set default values ​​for the parameters

  • Parameters with default values ​​are also optional
  • Parameters with default values ​​can be automatically deduced based on the value
function sort(items: Array<number>, order = 'desc') {}
sort([1,2,3]); // 默认参数order值为desc

// 也可以通过联合类型来限制取值
function sort(items: Array<number>, order:'desc'|'asc' = 'desc') {}
// ok
sort([1,2,3]);
// ok
sort([1,2,3], 'asc');
// error
sort([1,2,3], 'abc');

【3】Remaining parameters

The remaining parameters are an array, so be careful when labeling

interface IObj {
    [key:string]: any;
}
function merge(target: IObj, ...others: Array<IObj>) {
    return others.reduce( (prev, currnet) => {
        prev = Object.assign(prev, currnet);
        return prev;
    }, target );
}
let newObj = merge({x: 1}, {y: 2}, {z: 3});

Three, this in the function

Whether  JavaScript or  TypeScript function of  this all we need to be concerned, and that the function  this of the type, how to mark it?

【1】Ordinary function

For ordinary functions, it this will change with the change of the calling environment, so by default, the ordinary function  this is marked as  any, but we can be in the first parameter position of the function (it does not occupy the actual parameter position) Type of explicit annotation  this on

interface T {
    a: number;
    fn: (x: number) => void;
}

let obj1:T = {
    a: 1,
    fn(x: number) {
        //any类型
        console.log(this);
    }
}


let obj2:T = {
    a: 1,
    fn(this: T, x: number) {
        //通过第一个参数位标注 this 的类型,它对实际参数不会有影响
        console.log(this);
    }
}
obj2.fn(1);

[2] Arrow function

Arrow functions  this cannot be annotated like ordinary functions, and its this annotation type depends on the  annotation type of the scope this in which it is located 

interface T {
    a: number;
    fn: (x: number) => void;
}

let obj2: T = {
    a: 2,
    fn(this: T) {
        return () => {
            // T
            console.log(this);
        }
    }
}

Four, function overloading

Sometimes, the same function will receive different types of parameters and return different types of return values. We can use function overloading to achieve this. Use the following example to experience function overloading

function showOrHide(ele: HTMLElement, attr: string, value: 'block'|'none'|number) {
	//
}

let div = document.querySelector('div');

if (div) {
  showOrHide( div, 'display', 'none' );
  showOrHide( div, 'opacity', 1 );
	// error,这里是有问题的,虽然通过联合类型能够处理同时接收不同类型的参数,但是多个参数之间是一种组合的模式,我们需要的应该是一种对应的关系
  showOrHide( div, 'display', 1 );
}

Let's take a look at function overloading

function showOrHide(ele: HTMLElement, attr: 'display', value: 'block'|'none');
function showOrHide(ele: HTMLElement, attr: 'opacity', value: number);
function showOrHide(ele: HTMLElement, attr: string, value: any) {
  ele.style[attr] = value;
}

let div = document.querySelector('div');

if (div) {
  showOrHide( div, 'display', 'none' );
  showOrHide( div, 'opacity', 1 );
  // error 通过函数重载可以设置不同的参数对应关系
  showOrHide( div, 'display', 1 );
}
  • The overloaded function type only needs to define the structure, not the entity, similar to the interface
interface PlainObject {
    [key: string]: string|number;
}

function css(ele: HTMLElement, attr: PlainObject);
function css(ele: HTMLElement, attr: string, value: string|number);
function css(ele: HTMLElement, attr: any, value?: any) {
    if (typeof attr === 'string' && value) {
        ele.style[attr] = value;
    }
    if (typeof attr === 'object') {
        for (let key in attr) {
            ele.style[attr] = attr[key];
        }
    }
}

let div = document.querySelector('div');
if (div) {
    css(div, 'width', '100px');
    css(div, {
        width: '100px'
    });

    // error,如果不使用重载,这里就会有问题了
    css(div, 'width');
}

 

Articles are continuously updated every week. You can search for " Front-end Collection  " on WeChat to  read it for the first time, and reply to [ Video ] [ Book ] to receive 200G video materials and 30 PDF book materials

 

Guess you like

Origin blog.csdn.net/qq_38128179/article/details/115068983