我正在嘗試定義一個函式,它將物件映射屬性(字串)回傳到字串串列,除非串列中只有一個專案,然后我想映射到字串。
type MyType = { [key: string]: string | string[] }
export function myFunc(s: string): MyType {
const result: MyType = {}
for (const param of s.split('&')) {
const [key, val] = param.split(/=(.*)/s, 2)
if (Object.prototype.hasOwnProperty.call(result, key)) {
result[key].push(val ? val : '') // Type error happens here because there's no string.push()
} else {
result[key] = [val ? val : '']
}
}
for (const [key, val] of Object.entries(result)) {
if (val.length === 1) {
result[key] = val[0]
}
}
return result
}
在這里做什么是正確的?我可以將第一個for回圈移動到它自己的函式中,{ [key: string]: string[] }然后回傳,result: MyType = thatFunction()或者我可以有兩個變數
const _result: { [key: string]: string[] } = {}
// [do the first for loop]
const result = _result as MyType
// [do the second for loop]
return result
有沒有辦法做這種型別的事情,我想在我的代碼中寫一些給定型別的東西,然后立即將該值轉換為更嚴格/更寬松的型別而沒有中間變數名?
uj5u.com熱心網友回復:
好吧,使用括號表示法縮小型別是有限制的。但是有一個解決方法是將該屬性分配給臨時變數型別檢查它然后分配它:
const temp = result[key];
if (Array.isArray(temp)) { // you need to narrow down the type
temp.push(val ? val : '')
}
if (Array.isArray(result[key])) { // sadly this won't work
result[key].push(val ? val : '')
}
操場
編輯
由于您的代碼流保證它result[key]始終是一個陣列。您可以安全地斷言這是一個具有如下強制轉換的陣列:
( result[key] as string[]).push(val ? val : '')
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/451836.html
標籤:打字稿
