您将如何正确地为此声明类型?

interface MediaQueryProps {
  [key: string]: number;
}

const size: MediaQueryProps = {
  small: 576,
  medium: 768,
  large: 992,
  extra: 1200
};

export default Object.keys(size).reduce((acc, cur) => {
  acc[cur] = `(min-width: ${size[cur]}px)`;

  return acc;
}, {});

acc[cur]人抱怨是因为

Element implicitly has an 'any' type because expression of type 'string' can't be used to index type '{}'.
  No index signature with a parameter of type 'string' was found on type '{}'

有没有什么方法可以不使用任何?

推荐答案

如果你想让累加器的值以string为单位进行索引,Record<string, string>应该可以做到这一点.可以将其作为类型参数传递给reduce

interface MediaQueryProps {
  [key: string]: number;
}

const size: MediaQueryProps = {
  small: 576,
  medium: 768,
  large: 992,
  extra: 1200
};

export default Object.keys(size).reduce<Record<string, string>>((acc, cur) => {
  acc[cur] = `(min-width: ${size[cur]}px)`;
  return acc;
}, {});

Playground link

Typescript相关问答推荐

相交TypScript中的对象和接口

Angular 垫页分类和垫排序不起作用

之间是否有区别:例如useEffect()React.useEffect()

Tailwind CSS样式不在Svelte应用程序中呈现

类型脚本如何将嵌套的通用类型展开为父通用类型

对于使用另一个对象键和值类型的对象使用TS Generics

webpack错误:模块找不到.当使用我的其他库时,

在MessageStore对象中实现条件类型时出现TypeScrip错误

适当限制泛型函数中的记录

使用2个泛型类型参数透明地处理函数中的联合类型

TypeScrip省略了类型参数,仅当传递另一个前面的类型参数时才采用默认类型

如何创建一家Reduxstore ?

有什么方法可以类型安全地包装import()函数吗?

专用路由组件不能从挂钩推断类型

使用ngfor循环时,数据未绑定到表

类型脚本中参数为`T`和`t|unfined`的重载函数

如何实现允许扩展泛型函数参数的类型

如何在Vuetify 3中导入TypeScript类型?

如何通过nx找到所有受影响的项目?

我可以在 Typescript 中重用函数声明吗?