我有這些介面:
interface ParsedUrlQuery {
[key: string]: string | string[]
}
interface URLParams {
[key: string]: string
}
然后我撰寫函式:
const getParamsFromQuery = (query: ParsedUrlQuery): URLParams => {
return Object.fromEntries(
Object.entries(query).filter(([_key, value]) => typeof value === 'string')
)
}
我收到打字稿錯誤:
Type '{ [k: string]: string | string[]; }' is not assignable to type 'URLParams'.
'string' index signatures are incompatible.
Type 'string | string[]' is not assignable to type 'string'.
Type 'string[]' is not assignable to type 'string'.ts(2322)
為什么這不起作用,我需要什么讓打字稿考慮到這個過濾器動作?
uj5u.com熱心網友回復:
您正在尋找一個typeguard,它可以讓您告訴 typescript 如果您的函式回傳 true - then value is string。
const getParamsFromQuery = (query: ParsedUrlQuery): URLParams => {
return Object.fromEntries(
Object.entries(query).filter((kv): kv is [string, string] => typeof kv[1] === 'string')
)
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/522088.html
