typescript - 对象对象的 TypeScript 类型?
问题描述
什么是正确的打字稿类型
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
解决方案
索引签名参数类型必须是string
或number
:
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 }
}
推荐阅读
- c# - 在 C# 中添加一个双精度数
- ruby-on-rails - 如何模拟 Rails.cache.fetch 的 nil 情况?
- reactjs - Sonarqube Lcov 覆盖范围未显示
- javascript - 数据范围之间的函数计算仅适用于第一行
- javascript - 从多级嵌套对象数组中创建嵌套 JSX 列表项 reactjs
- vue.js - 使用切片的Vue js表
- sql-injection - SQL 注入格式检查绕过
- php - PHP Artisan Tinker 从任何命令崩溃
- python - Python List 返回与前两个值关联的第三个值
- ruby - 如何在 CentOS 6.9 上安装 Ruby?