使用TypeScript中使用MAP / FILFER的过滤类型使用过滤类型

发布于 2025-02-10 12:03:32 字数 505 浏览 2 评论 0原文

我意识到这个问题不是特定于打字稿的,但是留下以下行(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

https://onecompiler.com/typescript/3y88gzecj

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

https://onecompiler.com/typescript/3y88gzecj

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

素年丶 2025-02-17 12:03:32

当然,您需要使用convert filter回调到typeguard:


const array_: (String | Number)[] = [99, "Hello, World!"];

array_.map((e) => { if (typeof e === "string") console.log(e.length) }) // A

array_.filter(
  (e): e is string => typeof e === "string").map((e) => {
    console.log(e.length)
  }) // ok

callback (e):e是字符串=> E ===“字符串”

请参见 docs
playground

Sure, you need to use convert filter callback to typeguard:


const array_: (String | Number)[] = [99, "Hello, World!"];

array_.map((e) => { if (typeof e === "string") console.log(e.length) }) // A

array_.filter(
  (e): e is string => typeof e === "string").map((e) => {
    console.log(e.length)
  }) // ok

Callback (e): e is string => typeof e === "string"

Please see docs
Playground

寂寞花火° 2025-02-17 12:03:32

使用

const array_: (String| Number)[] = [99, "Hello, World!"];

const isString = (item: String | Number): item is String => typeof item === "string"

array_.map((e) => {if (typeof e === "string") console.log(e.length)})

array_.filter(isString).map((e) => {console.log(e.length)})

Use Type predicates so TS knows what you're doing

const array_: (String| Number)[] = [99, "Hello, World!"];

const isString = (item: String | Number): item is String => typeof item === "string"

array_.map((e) => {if (typeof e === "string") console.log(e.length)})

array_.filter(isString).map((e) => {console.log(e.length)})
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文