【问题标题】:Typescript won't allow me to access object property打字稿不允许我访问对象属性
【发布时间】:2019-08-13 11:44:15
【问题描述】:

我已经定义了一个对象:

const parsers = {
  belgianMobile: (input: string) =>
    input.replace(/^(0032|0)(\d{3})(\d{2})(\d{2})(\d{2})/, '$1$2 $3 $4 $5').replace('0032', '+ 32 '),
};

我现在想通过一个键来访问这个对象的属性(稍后当我添加多个解析器时):

const clean = cleanNumber(text);
  const [key] = Object.entries(validations).find(([key, regex]) => regex.test(clean));
  return ((parsers[key](text)) && parsers[key](clean)) || text;

但这是打字稿抛出的错误:

元素隐式具有“任何”类型,因为“字符串”类型的表达式不能用于索引类型“{ belgianMobile: (input: string) => string; }'。 在 '{ belgianMobile: (input: string) => string; 类型上找不到带有“string”类型参数的索引签名}'。

【问题讨论】:

    标签: typescript object key


    【解决方案1】:

    从上面我认为你想要这样的东西。

    const message: string = 'hello world';
    const parsers1 = [{
      belgianMobile: (input: string) =>
        input.replace(/^(0032|0)(\d{3})(\d{2})(\d{2})(\d{2})/, '$1$2 $3 $4 $5').replace('0032', '+ 32 '),
    },{
      belgianMobile1: (input: string) =>
        input.replace(/^(0032|0)(\d{3})(\d{2})(\d{2})(\d{2})/, '$1$2 $3 $4 $5').replace('0032', '+ 32 '),
    }];
    console.log(parsers1[0].belgianMobile(message));
    console.log(parsers1[1].belgianMobile1(message));
    

    【讨论】:

      【解决方案2】:

      我发现您需要键入要从中读取的对象本身,如下所示:

      const validations: { [key: string]: RegExp } = {
        belgianMobile: /^(0032|0)4\d{8}$/,
      };
      
      const parsers: { [key: string]: (input: string) => string } = {
        belgianMobile: input =>
          input.replace(/^(0032|0)(\d{3})(\d{2})(\d{2})(\d{2})/, '$1$2 $3 $4 $5').replace('0032', '+ 32 '),
      };
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-12-09
        • 2014-10-17
        • 2020-07-26
        • 1970-01-01
        • 2022-01-05
        • 2012-01-01
        • 1970-01-01
        • 2019-03-10
        相关资源
        最近更新 更多