【问题标题】:TypeScript historyMethod typeTypeScript 历史方法类型
【发布时间】: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


    【解决方案1】:

    因为您已经在代码中使用了as any,为什么不在此处也使用它呢?

    /**
     * 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 as any)[historyMethod + `State`]( { path: value }, ``, target ) // <- Error here
        return value
      }
    }
    

    【讨论】:

      猜你喜欢
      • 2015-07-24
      • 1970-01-01
      • 2018-08-26
      • 1970-01-01
      • 2010-12-17
      • 2020-04-03
      • 2021-11-01
      • 1970-01-01
      • 2016-07-01
      相关资源
      最近更新 更多