javascript - 在 typescript 中定义对象并访问它的值的最佳方法是什么?

标签 javascript typescript typescript-typings typescript2.0

我有一个格式的对象

export const IconSizeMap = {
  'extra-small': '0.75rem',
  small: '1rem',
  medium: '1.5rem',
  large: '2rem',
  'extra-large': '4rem'
};

作为 typescript 的新手,我无法理解错误是什么

报错

Element implicitly has an 'any' type because expression of type 'string' can't be used to index type '{ 'extra-small': string; small: string; medium: string; large: string; 'extra-large': string; }'.
  No index signature with a parameter of type 'string' was found on type '{ 'extra-small': string; small: string; medium: string; large: string; 'extra-large': string; }'.ts(7053)

当我尝试使用时

IconSizeMap[size]

我该如何解决这个错误?

最佳答案

您收到此错误是因为您的 tsconfig.json 启用了 "noImplicitAny": true。这意味着 TypeScript 会查找并通知您在哪些地方使用了类型未知的值,以及您没有明确告诉他应该是哪种类型。

您摆脱它的解决方案是:

  • 在配置中禁用 noImplicitAny (但我想这是有原因的,所以我不建议这样做)
  • 告诉 TypeScript 你正在使用的导致错误的类型。

在这里,TypeScript 识别出您定义的 5 个键中的每一个(extra-smallsmallmediumlargeextra-large),因为您为它们分配了一个 string 值,因此它可以判断它们是字符串。但是,只有这 5 个 string 是键。

当您使用“通用” string 来访问您的对象时,例如我假设您的 size 是什么,您不确定它是否对应于一个的 5 个键。所以,TypeScript 会警告你。

一种解决方案可能是告诉编译器您确定自己在做什么,并更准确地指定 size 的类型。例如:

export const IconSizeMap = {
  'extra-small': '0.75rem',
  small: '1rem',
  medium: '1.5rem',
  large: '2rem',
  'extra-large': '4rem'
};

let size: keyof typeof IconSizeMap; // Means "I'm sure that size is one of those strings
size = "small";

console.log(IconSizeMap[size]);

Playground link

关于javascript - 在 typescript 中定义对象并访问它的值的最佳方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63357074/

相关文章:

typescript - 为什么 Typescript 不允许使用整个精炼类型?

typescript - Vue Typescript 子组件方法

javascript - 如何正确地将 MSAL(用于 js 的 Microsoft 身份验证库)导入并使用到 typescript react 单页应用程序中?

typescript - 从联合类型 typescript 生成字符串数组

javascript - Redux,获取所有状态而不是我通过的状态

javascript - 使用d3.js修改c3.js图表

javascript - 如何记录在Google Analytics上点击的Instagram图像?

javascript - 错误: [$controller:ctrlreg] The controller with the name 'CreatePortfolioController' is not registered

node.js - 您无权查看 Azure Ionic App 的此目录或页面

javascript - TypeScript:找不到命名空间 'ng'