Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
4.1k views
in Technique[技术] by (71.8m points)

TypeScript函数重载中无法访问形参

假设我们有下面这样一个重载函数,可以不传参数,也可以传入两个或者四个,现在这样的写法在ts中会报错

function show(): void;
function show(x: number, y: number): void;
function show(x: number, y: number, w: number, h: number): void;
function show(...args: any[]): void {
  console.log(x); // Cannot find name 'x'
}
show();

这样的写法有问题么


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

image.png

给你一个修改建议:

function show(): void;
function show(x: number, y: number): void;
function show(x: number, y: number, w: number, h: number): void;
function show(x?: number, y?: number, w?: number, h?: number): void {
    if (x !== undefined && y !== undefined) {
        console.log(`${x} and ${y} are valid number now`);
        console.log("calc result:", x + y);
    }

    if (w !== undefined && h !== undefined) {
        console.log(`${w} and ${h} are valid number now`);
        console.log("area size: ", w * h);
    }
}

说明:

  1. 实现时的参数列表,必须兼容所有声明。比如上面实现时所有参数可选,是为了兼容 show() 这个声明
  2. 实现时对 x, y, w, h 分别进行了非 undefined 判断,可以保证分支中它们不是 undefined,所以可以直接使用(如果不加判断是不能直接参与运算的)

欢迎来学习我的课程:TypeScript从入门到实践 【2020 版】

3.2 节的 2分20秒 左右讲到了相关的问题

image.png


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...