Typescript不允许我访问对象属性

时间:2019-08-13 11:44:15

标签: typescript object key

我已经定义了一个对象:

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;

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

  

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

2 个答案:

答案 0 :(得分: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));

答案 1 :(得分:0)

我发现您需要像这样输入对象本身:

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 '),
};