简体   繁体   English

如何处理 Typescript 中的错误返回类型?

[英]How do handle Error return types in Typescript?

I have a function that can return either an object of type Person or an Error.我有一个函数可以返回一个 Person 类型的对象或一个 Error 类型的对象。 I want to conditionally read the values of keys in the returned object if it's not an Error.如果不是错误,我想有条件地读取返回对象中键的值。

The last line of the code snippet below gives an error:下面代码片段的最后一行给出了一个错误:

Property 'firstName' does not exist on type 'Person |类型 'Person | 中不存在属性'firstName' Error'错误'

The error can be seen at this link .该错误可以在此链接中看到。

 interface Person { firstName: string; lastName: string; } function greeter(person: Person): Person | Error { if (person.firstName === 'Malcolm') { return new Error('This firstName is not allowed'); } return { firstName: person.firstName, lastName: person.lastName, }; } const x = greeter({ firstName: "Malcolm", lastName: "Reynolds", }); const { firstName, lastName } = x;

I have to return the Error for some scenarios.对于某些情况,我必须返回错误。 Can't skip it.不能跳过。

Thanks in advance!提前致谢!

Firstly I would suggest you to wrap greeter() inside try ... catch block to handle the error.首先,我建议您将greeter()包装在try ... catch块中以处理错误。

Still if you want to do it this way, you can do the following.如果你想这样做,你可以执行以下操作。

const val = greeter({
    firstName: "Malcolm",
    lastName:  "Reynolds",
})

if (typeof val == Person) { 
const x = val as Person;
const {firstName, lastName} = x;
}

Here you can check the type of result and perform operation accordingly.在这里您可以检查结果的类型并进行相应的操作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM