我试着写判断字符串的函数.如果字符串包含重复符号,则该函数返回FALSE.如果字符串没有重复符号,则返回TRUE.这是我的try :

function isIsogram(str: string): boolean {
  const lower = str.toLocaleLowerCase();
  let db: Record<string, number> = {};

  db = lower.split('').reduce((acc, item) => {
    if (item in acc) {
      acc[item]++; // error: Element implicitly has an 'any'
    } else {
      acc[item] = 1; // error: Element implicitly has an 'any'
    }

    return acc;
  }, {});

  return Object.values(db).every((i) => i === 1);
}

console.log(isIsogram('')); // true
console.log(isIsogram('Dermatoglyphics')); // true
console.log(isIsogram('isogram')); // true
console.log(isIsogram('aba')); // false
console.log(isIsogram('moOse')); // false
console.log(isIsogram('isIsogram')); // false

live demo is here

这是正确的工作代码,但是我从TypeScrip解析器收到以下错误消息:

元素隐式具有""any""类型,因为 "字符串"不能用于索引类型"{}".不带索引签名 在类型‘{}’上找到类型为‘STRING’的参数.(7053)

请帮我修改我的代码.我需要删除那个错误消息.但我需要使用即Reduce()函数.

推荐答案

REDUTE函数的初始值是无类型的,因此acc也是无类型的.REDUTE的模板参数解决了这个问题.

interface AssociativeNumberArray {
  [key: string]: number
}

[...]

  db = lower.split('').reduce<AssociativeNumberArray>((acc, item) => {

Typescript相关问答推荐

当使用`type B = A`时,B的类型显示为A.为什么当`type B = A时显示为`any `|用A代替?

动态调用类型化函数

在Angular中注入多个BrowserModules,但在我的代码中只有一个

使用ngrok解析Angular 时出现HTTP故障

分解对象时出现打字错误

TypeScrip泛型类未提供预期的类型错误

将对象的属性转换为正确类型和位置的函数参数

Typescript -返回接口中函数的类型

自动通用回调

字幕子集一个元组的多个元素

基于闭包类型缩小泛型类型脚本函数的范围

如何使对象同时具有隐式和显式类型

如何提取具有索引签名的类型中定义的键

为什么类方法参数可以比接口参数窄

两个接口的TypeScript并集,其中一个是可选的

数据库中的表请求返回如下日期:2023-07-20T21:39:00.000Z 我需要将此数据格式化为 dd/MM/yyyy HH:mm

Angular另一个组件的nativeelement未定义

广义泛型类型不加载抽象类型上下文

包含多个不同类构造函数的接口的正确类型?

为什么我们在条件语句中使用方括号[]?