如何在TypeScript中正确键入函数

时间:2019-08-27 17:35:57

标签: typescript

我正在尝试在TypeScript中键入一个函数:

这里一切都很好

const myFunction_1 = (param1: number, param2: number): number => {
    return param1 + param2;
};

const result_1 = myFunction_1(1, 2);
console.log(result_1);

此处显示错误,因为未返回任何内容:A function whose declared type is neither 'void' nor 'any' must return a value.

const myFunction_2 = (param1: number, param2: number): number => {};

const result_2 = myFunction_2(1, 2);
console.log(result_2);

这里一切都很好

type myFunction_3Type = (param1: number, param2: number) => number;

const myFunction_3: myFunction_3Type = (param1: number, param2: number) => {
    return param1 + param2;
};

const result_3 = myFunction_3(1, 2);

这是有趣的部分。我声明了两个接口:一个用于函数的输入,另一个用于输出。我以myFunction_4Type类型使用它们;然后,我在函数中使用此类型,并强制该函数返回与输出接口不匹配的对象。但它不会显示错误!

interface IMyFunctionInput {
    a: number;
    b: number;
}

interface IMyFunctionOutput {
    a: number;
    b: number;
}

type myFunction_4Type = (payload: IMyFunctionInput) => IMyFunctionOutput;

const myFunction_4: myFunction_4Type = payload => {
    return {
        a: 1,
        b: 2,
        c: 3 // This key and prop should cause an error, as it doesn't match the interface IMyFunctionOutput
    };
};

const payload = {
    a: 1,
    b: 2
};

const result_4 = myFunction_4(payload);

欢迎任何帮助:)

1 个答案:

答案 0 :(得分:2)

您似乎有两个不同的问题。第一个是lst = df.apply(reform, axis=1).tolist() pd.concat(lst).reset_index(drop=True) 您的函数A function whose declared type is neither 'void' nor 'any' must return a value.的声明返回类型为myFunction_2,但是函数体为number,它什么也不返回。

您有两个选择,可以将返回类型定义为{ }

void

或返回数字:

const myFunction_2 = (param1: number, param2: number): void => {};

第二个问题是TypeScript的功能:https://www.typescriptlang.org/docs/handbook/interfaces.html#excess-property-checks

一种选择是首先将其分配给变量,以利用文档中所述的多余属性检查:

  

对象文字在分配给其他变量或作为参数传递时会受到特殊对待,并进行多余的属性检查。如果对象文字具有“目标类型”所没有的任何属性,则会出现错误:

const myFunction_2 = (param1: number, param2: number): number => { return 1 };

jcalz指出的另一种选择:

const myFunction_4: myFunction_4Type = payload => {
    const value: IMyFunctionOutput = {
        a: 1,
        b: 2,
        c: 3 // Object literal may only specify known properties, and 'c' does not exist in type 'IMyFunctionOutput'.
    };

    return value;
};

另外,请参阅此概述以了解更多详细信息:https://basarat.gitbooks.io/typescript/docs/types/freshness.html

此处共享了另一种可能的解决方案:https://stackoverflow.com/a/54775885/2690790