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
3.9k views
in Technique[技术] by (71.8m points)

typescript 返回值类型 根据参数确定 布尔类型

请问 Typescript 语言中

如果一个函数的返回值有多种的话

/// 比如:
declare function foo(p : boolean) : number | string;

要如何根据参数 p 确定返回值类型?

/// 就是,达到如下效果:
declare function foo(p : true) : number;
declare function foo(p : false) : string;

类似于 document.querySelector 函数的定义
有所不同的是

  • document.querySelector 的参数是 字符串 类型的
  • 这里想实现的布尔 类型的

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

1 Answer

0 votes
by (71.8m points)

可以用函数重载实现

function foo(p: true): number;
function foo(p: false): string;
function foo(p: any): any {
    if (p === true) {
        // ...
    } else {
        // ...
    }
}

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

...