【发布时间】:2021-04-14 01:59:25
【问题描述】:
在阅读了history方法的documentation之后,我不确定如何使用TypeScript来实现它。我得到的错误是string 类型不能用于索引History:
元素隐式具有“any”类型,因为“string”类型的表达式不能用于索引“History”类型。
在“历史”类型上找不到带有“字符串”类型参数的索引签名。
在我将原始 JS 转换为 TS 之前,这是可行的。您将如何解决这个问题?
/**
* Handles the query parameters.
* @param {String} key The key in the URL.
* @param {String} value The value in the URL.
* @param {Object} options The options of the key-value pair.
*/
const handleParam = (
key: string, value: string | null | undefined, options: object = {}
) => {
// Server-side rendering does not have a window object. Don't query on SSR.
if ( typeof window !== `undefined` ) {
// historyMethod: push or replace
// (https://developer.mozilla.org/docs/Web/API/History)
const { historyMethod = `replace`, nullDeletes = true } = options as any
const params = new URLSearchParams( location.search )
if ( value === undefined ) value = params.get( key )
else if ( value === null && nullDeletes ) params.delete( key )
else params.set( key, value as any )
let target = window.location.pathname + `?` + params.toString()
target = target.replace( /\/?\?$/, `` ) // remove empty search string
history[historyMethod + `State`]( { path: value }, ``, target ) // <- Error here
return value
}
}
【问题讨论】:
标签: typescript