对象的TypeScript类型为object?

亚历克斯

像这样的正确打字稿类型是什么

const test: MyType = {
  foo: { value: 1 },
  bar: { value: 2 }
}

就像是

type MyType {
  [key: any]: {
    value:number
  }
}

结果是

Object literal may only specify known properties, and 'foo' does not exist in type 
彭格

索引签名参数类型必须为stringnumber

type MyType = {
    [key: string]: { value: number; };
};

const test: MyType = {
    foo: { value: 1 },
    bar: { value: 2 }
};

或者,使用Record

const test: Record<string, { value: number }> = {
    foo: { value: 1 },
    bar: { value: 2 }
}

const test: Record<'foo' | 'bar', { value: number }> = {
    foo: { value: 1 },
    bar: { value: 2 }
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

如何根据 switch case 为 TypeScript 中的对象分配类型

Typescript无法为函数对象推断正确的参数类型

在TypeScript中将任意函数参数推断为对象或元组类型

对象的类型为“未知”。ts(2571) 与 Vuejs 和 Typescript

Object.keys - 元素在 Typescript 中隐含类型为“any”

将类型为List <object>的对象转换为List <string>

如何将TypeScript对象类型转换为TypeScript中的联合类型,如Object.values()?

Typescript对象属性类型

TypeScript对象类型

从对象=>对象映射TypeScript类型

TypeScript / Vue 3:注入变异函数导致 TypeScript 错误“对象类型为‘未知’”

为什么Typescript允许为类对象分配“任意”对象类型?

在 Typescript 中,try...catch 错误对象显示“对象的类型为 'unknown'.ts(2571)”

Angular / Typescript找不到类型为“对象”的其他支持对象“ [对象对象]”。NgFor仅支持绑定到数组等Iterables

Angular bootstrap 搜索错误找不到类型为“object”的不同支持对象“[object Object]”

错误:找不到类型为'object-Angular 7的其他支持对象'[object Object]'

找不到类型为“object”的不同支持对象“[object Object]”,流星集合中出错

找不到类型为“object”的不同支持对象“[object Object]”。NgFor 仅支持

Angular 12:找不到类型为“object”的不同支持对象“[object Object]”

如何告诉TypeScript对象[foo]的类型是所有可能的object.prop类型的子集

TypeScript类型'Promise <void | 无法在Promise.then()上将Object>'分配为键入'Promise <Object>'

ngBootstraps typeaheade导致错误:找不到类型为'object'的其他支持对象'[object Promise]'

Angular NgRx存储类型错误:无法分配为只读对象“ [object Object]”的属性“ primary”

Typescript:如何在React中为历史对象添加类型检查?

如何在TypeScript中为具有动态属性的对象定义类型

如何使用 Typescript 和 useState 将类型对象设置为 React 的初始值?

Typescript-将类类型存储为变量,以便从中创建对象或其他等效功能

在TypeScript中,为具有必需属性的任何对象定义一种类型

如何在Typescript中为对象数组声明数据类型?