簡體   English   中英

如何在TypeScript中正確鍵入函數

[英]How properly type a function in 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);

任何幫助都將受到歡迎:)

看來您有兩個不同的問題。 第一個是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 => {};

或返回一個數字:

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

第二個問題是TypeScript的功能: https : //www.typescriptlang.org/docs/handbook/interfaces.html#excess-property-checks

一種選擇是首先將其分配給變量,以利用文檔中所述的多余屬性檢查:

將對象文字分配給其他變量或將其作為參數傳遞時,將對其進行特殊處理並進行過多的屬性檢查。 如果對象文字具有“目標類型”所不具有的任何屬性,則會出現錯誤:

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;
};

jcalz指出的另一種選擇:

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

另外,請參閱此概述以了解更多詳細信息: https : //basarat.gitbooks.io/typescript/docs/types/freshness.html

此處共享了另一個可能的解決方案: https : //stackoverflow.com/a/54775885/2690790

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM