打字稿 - 类型铸件未返回假冒值,如预期
如果类型不匹配,我希望在运行时铸造字符串以返回假值。也就是说,当我使用,我遇到了意外的结果:
$ ts-node
> 0 as 'B' | 'C' | 'D' || 'foo' // ✅ throws precompiler error as expected
--------------
> '' as 'B' | 'C' | 'D' || 'foo' // ✅ prints 'foo' as expected
'foo'
> undefined as 'B' | 'C' | 'D' || 'foo' // ✅ prints 'foo' as expected
'foo'
> null as 'B' | 'C' | 'D' || 'foo' // ✅ prints 'foo' as expected
'foo'
> 'B' as 'B' | 'C' | 'D' || 'foo' // ✅ prints 'B' as expected
'B'
> 'A' as 'B' | 'C' | 'D' || 'foo' // ❌ prints 'A' instead of 'foo' <-- UNEXPECTED
'A'
我清楚地误解了铸造的工作原理,但是我如何实现我试图实现我期望'a''as'b'|的逻辑。 'C'| 'd'
返回虚假值?
I would like the casting of a string at runtime to return a falsey value if the type is mismatched. Namely, when I run the following with [email protected]
, I encounter unexpected results:
$ ts-node
> 0 as 'B' | 'C' | 'D' || 'foo' // ✅ throws precompiler error as expected
--------------
> '' as 'B' | 'C' | 'D' || 'foo' // ✅ prints 'foo' as expected
'foo'
> undefined as 'B' | 'C' | 'D' || 'foo' // ✅ prints 'foo' as expected
'foo'
> null as 'B' | 'C' | 'D' || 'foo' // ✅ prints 'foo' as expected
'foo'
> 'B' as 'B' | 'C' | 'D' || 'foo' // ✅ prints 'B' as expected
'B'
> 'A' as 'B' | 'C' | 'D' || 'foo' // ❌ prints 'A' instead of 'foo' <-- UNEXPECTED
'A'
I clearly misunderstand how casting works, but how do I implement the logic I am trying to achieve where I expected 'A' as 'B' | 'C' | 'D'
to return a falsey value?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
是是一种类型断言,它没有运行时效应。您需要对值进行一些手动检查。类似:
然后您可以断言值是
'b'| 'C'| 'D'| 'foo'
使用为
。Playground (runnable)
Playground using type-fu to not repeat literals
as
is a type assertion, it does not have a runtime effect. You need to do some manual checking of the value instead. Something like:You then can assert that value is
'B' | 'C' | 'D' | 'foo'
usingas
.Playground (runnable)
Playground using type-fu to not repeat literals
我认为,与未知文字合作的“最清洁”方法是使用类型的后卫。
The "cleanest" way to work with unknown literals in my opinion is using a type guard.