簡體   English   中英

TypeScript 或者返回類型未檢測到屬性

[英]TypeScript either or return type is not detecting properties

type MyReturnType = Promise<boolean> | void

interface TestInterface {
    testFunction(): MyReturnType;
}

class TestClass implements TestInterface {
    testFunction() {
    }
}

const testObject = new TestClass();
testObject.testFunction()
    .then(() => { });

為什么會出現以下錯誤?

Property 'then' does not exist on type 'void'.

我錯過了什么嗎?

當您使用聯合類型(由 pipe 字符“|”表示)時,您不能假設testFunction將返回一種或另一種類型。

首先,您必須檢查testFunction在調用后返回的類型。

const result = testObject.testFunction()
if (result instanceof Promise) {
    result.then(() => {});
}

暫無
暫無

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

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