简体   繁体   English

typescript 类型声明在 IDE 中显示错误

[英]typescript type declaration shows error in IDE

I have the following type definition:我有以下类型定义:

export type AuthType = boolean | { roles: string[]; assistant?: string[] } | (() => void);

Now I have a line of code in which I want to check the type of my auth variable and assign a value or execute a function:现在我有一行代码,我想在其中检查auth变量的类型并分配一个值或执行一个函数:

req.allowed = auth === true ? this.allowed : auth.roles ? auth : auth();

The code works fine (this line is only executed if auth is not false or null) but my IDE (webstorm) shows me the following error:代码工作正常(仅当 auth 不为 false 或 null 时才执行此行),但我的 IDE (webstorm) 显示以下错误:

在此处输入图片说明

You haven't checked whether or not auth is an object, so typescript is trying to prevent you from accessing the roles property on a function (which doesn't exist).您尚未检查auth是否为对象,因此打字稿试图阻止您访问函数(不存在)上的roles属性。 Note that this won't throw an error but might be confusing to a future reader of the code.请注意,这不会引发错误,但可能会让未来的代码读者感到困惑。

The way you have it set up, you probably want to use the optional chaining operator :根据您的设置方式,您可能想要使用可选的链接运算符

req.allowed = auth === true ? this.allowed : auth?.roles ? auth : auth();

This will make it so that auth?.roles evaluates to undefined if it is a function.这将使auth?.roles评估为 undefined 如果它是一个函数。

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

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