【问题标题】:Index signature with typescript带有打字稿的索引签名
【发布时间】:2018-09-05 16:04:45
【问题描述】:

在打字稿中启用“noImplicitAny”时,我无法确定正确的索引签名是什么。

const getFromUri = () => {
  const urlSearch = window.location.search.substring(1);
  const params: { foo?: number; bar?: number } = {};
  if (urlSearch && urlSearch.length > 0) {
    const urlParams = urlSearch.split("&");
    urlParams.forEach((e: string) => {
      const obj = e.split("=");
      params[obj[0]] = obj[1];
    });
  }    
};

它在最后一行说: 错误:(17, 11) TS7017:元素隐式具有“任何”类型,因为类型 '{ foo?: number;酒吧?:号码; }' 没有索引签名。

【问题讨论】:

    标签: typescript index-signature


    【解决方案1】:

    你可以这样做:

    const getFromUri = () => {
      const urlSearch = window.location.search.substring(1);
    
      // Always extract useful types
      type Params = { foo?: number; bar?: number };
    
      const params: Params = {};
      if (urlSearch && urlSearch.length > 0) {
        const urlParams = urlSearch.split("&");
        urlParams.forEach((e: string) => {
          // Assume key here
          const obj = <[keyof Params, string]>e.split("=");
    
          // Forgot to parse
          params[obj[0]] = parseInt(obj[1]);
        });
      }    
    };
    

    顺便说一句,不要这样做。只需使用 URL 类或 polyfill/library 即可获取搜索参数。

    【讨论】:

    • 标准的 URL 类已经有了你需要的一切,试试:Array.from(new URL(document.location.href).searchParams)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-12-15
    • 1970-01-01
    • 1970-01-01
    • 2020-02-19
    • 2019-11-14
    • 1970-01-01
    • 2021-05-20
    相关资源
    最近更新 更多