使用TypeScript中使用MAP / FILFER的过滤类型使用过滤类型
我意识到这个问题不是特定于打字稿的,但是留下以下行(b)未注册会出现错误属性'长度'不存在类型'字符串|数字'
。是否有某种方法可以使打字稿知道所有元素现在仅是字符串(完成过滤后)?
const array_: (String| Number)[] = [99, "Hello, World!"];
array_.map((e) => {if (typeof e === "string") console.log(e.length)}) // A
// array_.filter((e) => typeof e === "string").map((e) => {console.log(e.length)}) // B
I realise this question is not specific to typescript, but leaving the below line (B) uncommented would give an error Property 'length' does not exist on type 'String | Number'
. Is there some way to make it possible for typescript to know that all the elements are now only string (after the filtering is done)?
const array_: (String| Number)[] = [99, "Hello, World!"];
array_.map((e) => {if (typeof e === "string") console.log(e.length)}) // A
// array_.filter((e) => typeof e === "string").map((e) => {console.log(e.length)}) // B
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
当然,您需要使用convert
filter
回调到typeguard:callback
(e):e是字符串=> E ===“字符串”
请参见 docs
playground
Sure, you need to use convert
filter
callback to typeguard:Callback
(e): e is string => typeof e === "string"
Please see docs
Playground
使用
Use Type predicates so TS knows what you're doing