繁体   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