[英]How to use assertion in destructuring syntax?
In Typescript, how can I use assertion in destructuring? Typescript,如何在解构中使用断言?
type StringOrNumber = string | number
const obj = {
foo: 123 as StringOrNumber
}
const { foo } = obj
I didn't find a convenient way to add number
type assertion on const foo
.我没有找到在 const
foo
上添加number
类型断言的便捷方法。 Two workarounds are:两个解决方法是:
// A:
const { foo } = obj as { foo: number }
// B:
const { foo: foo2 } = obj
const foo = <number>foo2
The first is a burden to rewrite the obj
's type when its type is nested and complicated.第一个是当
obj
的类型嵌套且复杂时重写其类型的负担。 The second seems weird.第二个看起来很奇怪。 I'm assuming such a syntax like:
我假设这样的语法:
const { <number>foo } = obj
can absolutely help us asserting the type from nested and complicated destructuring.绝对可以帮助我们从嵌套和复杂的解构中断言类型。
According to the documentation , there is no way for casting the type right when destructuring.根据文档,解构时无法正确转换类型。 Apparently, there are no workarounds other than those that you provided.
显然,除了您提供的解决方法外,没有其他解决方法。
I believe there are no possible way to do type assertion in destructuring objects or arrays.我相信没有办法在解构对象或 arrays 中进行类型断言。
But here are an alternative you can try.但这里有一个您可以尝试的替代方案。
const { foo, bar } = data;
const baz = foo as string;
// You can use string methods here.
console.log(baz.split(" "));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.