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)
当然,您需要使用转换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"
| 归档时间: |
|
| 查看次数: |
651 次 |
| 最近记录: |