TypeScript 中函数的返回类型

Shuvayan Ghosh Dastidar 2023年1月30日
  1. 在 TypeScript 的函数中为 return 语句使用类型
  2. 在 TypeScript 中使用 ReturnType 类型获取函数的返回类型
TypeScript 中函数的返回类型

TypeScript 是一种强类型语言,始终鼓励为 TypeScript 中使用的所有变量正确定义类型。这些类型可以在以后帮助开发,尤其是在调试期间。

除了变量之外,函数还可以具有返回类型的类型。通常,当未定义类型时,编译器会根据返回的变量类型自动推断类型。

但是,这很不方便,并且可能会导致像 any 甚至 undefined 这样的不太严格的类型作为返回类型,因此最好将类型返回给 TypeScript 函数。

在 TypeScript 的函数中为 return 语句使用类型

如果未提及任何类型,TypeScript 编译器会自动推断返回类型。最好向函数添加类型以确保通过应用程序代码传递正确的类型。

下面展示了如何将类型添加到 TypeScript 函数中。

function addTwoNumbers( a : number, b : number) : number {
    return a + b;
}

console.log(addTwoNumbers(5,6));

输出:

11

因此 number 类型已添加到 addTwoNumbers 的末尾,因此它表示函数 addTwoNumbers 的返回类型是 number 类型。TypeScript 支持联合和复杂类型作为函数的返回类型。

以下示例显示了类型联合作为函数的返回类型的示例。

function conditionalAdd(a : number, b : number ) : number | string {
    if ( a + b > 20){
        return "more than 20!";
    } else {
        return a + b;
    }
}

console.log(conditionalAdd(3,21));

输出:

"more than 20!"

甚至可以将接口作为函数的返回类型。假设有一个返回所有配置信息的函数。

它可以如下实现。

interface Config {
    logLevel : string,
    cache : boolean,
    dbUrl : string,
    password : string,
    production : boolean,
    version : number
}


function getConfig() : Config {
    return {
        logLevel : "debug",
        cache : true,
        dbUrl : "localhost:5432",
        password : "postgres",
        production : false,
        version : 2
    }
}

使用这种方法的好处是可以直接返回对象而无需声明变量并在开发过程中获得建议。

在 TypeScript 中使用 ReturnType 类型获取函数的返回类型

ReturnType 类型对于了解函数的类型很有用,该函数可能由用户编写,也可能不由用户编写,因为它可能在第三方库中。以下代码段显示了 ReturnType 类型如何检测返回类型。

function findStudentWithRoll(roll : number){
    const students : Student[] = [
        {
            name : 'Tintin',
            roll : 1,
            passed : true
        },
        {
            name : 'Haddock',
            roll : 2,
            passed : false
        },
        {
            name : 'Calculus',
            roll : 3,
            passed : true
        },
    ];
    return students.find( student => student.roll === roll) || null;
}


const studentRoll_1 : ReturnType<typeof findStudentWithRoll> = findStudentWithRoll(1);
if ( studentRoll_1 !== null){
    console.log(studentRoll_1);
}

输出:

 {
  "name": "Tintin",
  "roll": 1,
  "passed": true
}

因此,ReturnType<typeof findStudentWithRoll> 方便地返回 Student | null 进一步用于编写应用程序逻辑。

Shuvayan Ghosh Dastidar avatar Shuvayan Ghosh Dastidar avatar

Shuvayan is a professional software developer with an avid interest in all kinds of technology and programming languages. He loves all kinds of problem solving and writing about his experiences.

LinkedIn Website