打字稿将普通字符串转换为 Map

时间:2021-06-29 19:15:42

标签: javascript string typescript split

我有这个字符串(称为统计信息):

class WorkoutListTabViewModel : ViewModel(){
    private val _tab = MutableLiveData<String>()
    val tab get() = _tab
    private val list = listOf(
        "CHEST", "BACK", "LEG", "SHOULDER", "BICEPS", "TRICEPS", "ABS"
    )

    fun set(pos: Int) {
        _tab.value = list[pos]
    }
}

甚至不是 JSON 格式。

This 是我正在尝试的解决方案:

active_total: 1087
cumulative: 1
trace_total: 10

但它在这一行抛出编译错误:

let keyValuePairs = stats
  .split(/\s*\n\s*/)                     //split with optional spaces around the comma
  .map(chunk => chunk.split(": "));      //split key=value
  
const map = new Map(keyValuePairs);

console.log(map.get("sessions_active_total"));
console.log(map.get("cumulative"));

错误信息:

const map = new Map(keyValuePairs);

1 个答案:

答案 0 :(得分:0)

Typescript 无法推断出 chunk.split(": ") 的确切结果。即使能够远程猜测它,打字稿也应该知道 stats 变量的运行时值。

如果您正在寻找类型安全的解决方案,我假设您使用 custom type predicate

const isTupleOf2 = (chunk: string[]): chunk is [string, string] => chunk.length === 2

let keyValuePairs = stats
  .split(/\s*\n\s*/)
  .map((chunk: string) => chunk.split(": "))
  .filter(isTupleOf2)      
  
const map = new Map(keyValuePairs);

playground link

或者,如果您绝对确定结果将始终是您期望的结果,则可以使用 type assertion

let keyValuePairs = stats
  .split(/\s*\n\s*/)
  .map((chunk: string) => chunk.split(": ") as [string, string])

const map = new Map(keyValuePairs);

playground link