在 Typescript 中使用映射/过滤器来处理过滤类型

use*_*604 2 functional-programming filter typescript

我意识到这个问题并不是特定于打字稿的,但是如果不注释下面的 (B) 行,则会出现错误Property 'length' does not exist on type 'String | Number'。有没有什么方法可以让打字稿知道所有元素现在只是字符串(过滤完成后)?

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
Run Code Online (Sandbox Code Playgroud)

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

cap*_*ian 5

当然,您需要使用转换filter回调来类型保护:


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
Run Code Online (Sandbox Code Playgroud)

打回来(e): e is string => typeof e === "string"

参阅文档