[英]Unsafe assignment of an Any value ternary operator
I have a doubt related to typescript, and how I can work with union types to make it work.我对打字稿有疑问,以及如何使用联合类型使其工作。 Currently I have this code:
目前我有这个代码:
const message: string | string[] = (axiosError as Error).message
const errorState: string | string[] = Array.isArray(message)
? message[0]
: message
The issue I get is in errorStat variable, I know the cause, it is because I am trying to access message[0] and it can be of type string and have no data inside.我得到的问题是在 errorStat 变量中,我知道原因,这是因为我试图访问 message[0] 并且它可以是字符串类型并且里面没有数据。 I know I always got a value inside message.
我知道我总是在消息中获得价值。
Any help?有什么帮助吗?
Thanks!谢谢!
There are a number of places where this will trip up.有很多地方会发生这种情况。
The biggest one is that Array.isArray
and the other answerer's isArray
type guards only assert whether or not the given type is any[]
, not any particular T[]
.最大的一个是
Array.isArray
和其他回答者的isArray
类型保护只断言给定类型是否为any[]
,而不是任何特定的T[]
。 If the type guard fails, the type checker knows for sure the type is string
.如果类型保护失败,类型检查器肯定知道类型是
string
。 But if it passes, the type checker only knows that it's any[]
and can't figure out anything beyond that.但如果它通过了,类型检查器只知道它是
any[]
并且无法找出除此之外的任何内容。
If, instead, you had this type guard:相反,如果你有这个类型保护:
function isTypedArray<T>(val: T | T[]): val is T[] {
return isArray(val);
}
Then the type checker will be able to differentiate between string
and string[]
.然后类型检查器将能够区分
string
和string[]
。
However, you're then storing it in a variable that you have explicitly typed as string | string[]
但是,您随后将其存储在您已明确键入为
string | string[]
的变量中。 string | string[]
, so when you subsequently try to use errorMessage
, the type checker will still be confused about the type. string | string[]
,因此当您随后尝试使用errorMessage
时,类型检查器仍然会对类型感到困惑。 Remove the type annotation from errorMessage
, or change it to just string
.从
errorMessage
中删除类型注释,或将其更改为string
。
Finally, this might not be an issue for your particular use case, but you have a potential bug if axiosError
's message
field is an empty array.最后,对于您的特定用例,这可能不是问题,但如果
axiosError
的message
字段是空数组,则可能存在错误。 The type checker will assert that you have an array, but then when you try to access the value of it at runtime, it will return as undefined
.类型检查器将断言您有一个数组,但是当您尝试在运行时访问它的值时,它将返回为
undefined
。 That might be acceptable in your situation, but I don't know.在你的情况下这可能是可以接受的,但我不知道。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.