[英]Retrieve the value of a List/Map the proper way with Immutable JS in TypeScript
我已經使用 Immutable JS 幾個月了。 我真的很喜歡它提供的功能。 但是我一遍又一遍地做着我不喜歡的事情。 它與從 List 或 Map 中檢索值有關。
在檢索這個值時,我首先檢查它是否存在,當它存在時,我想進一步與它交互。 但直到今天,我仍然不知道如何做到這一點“正確的方式”。
我知道我正在寫的內容可能會更好,因為我已經看到了 fp-ts 等功能框架中的功能(如折疊)。 所以我知道必須有更好的方法從 List/Map 中檢索值。
有誰知道怎么做?
我將在下面添加一些代碼示例以及指向源代碼的鏈接:
import { Map, List } from 'immutable'
import { pipe } from 'fp-ts/function'
import { fold } from 'fp-ts/boolean'
// Example 1 - with Map
type Person = {
name: string
surname: string
age: number
}
const persons = Map<number, Person>()
.set(1, {name: 'Jack', surname: 'Bright', age: 25})
.set(2, {name: 'Jane', surname: 'Bright', age: 22})
.set(3, {name: 'Mike', surname: 'Bright', age: 21})
const someProgram = (id: number = 2) => {
// ... Does some things
// We need to update a user with id: 2
if (persons.has(id)) {
// This is where the problem is. We know that the person exists, because we're in the true clause. But still we get undefined as possible value.
const person1 = persons.get(id) // Person | undefined
// Now we add the ! and it works, but this is not nice nor elegant. What is the proper way of doing this (getting an element)?
const person2 = persons.get(id)! // Person
} else {
console.log('Error')
}
}
// Example 2 - With fp-ts & List
/**
* I use fp-ts a lot lately, and even with this I get this ugly way of adding the ! at every retrieval.
* An example with List<Person>. We want to get the first Person in the list if the list isn't empty.
*/
pipe(persons.isEmpty(), fold(
// onFalse
() => console.log('Error'),
// onTrue
() => {
// We know that there is a user in this clause. But how do we get it properly?
const person1 = persons.get(0) // Person | undefined
const person2 = persons.get(0)! // Person
}
))
這聽起來像是一個未解決的 TS 問題。 它與 ImmutableJS 沒有直接關系,更多的是 TS 中可為空的 getter 函數的一般問題。
您可以通過省略has
檢查來重寫代碼:
const person = persons.get(id);
if(person) {
// do stuff
}
或者persons.get(id, DEFAULT_PERSON)
可能總是返回一個人 object,但是你必須這樣做if(person === DEFAULT_PERSON)
這比感嘆號更難看
或者您禁用 strictNullChecks。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.