typescript - 打字稿:有条件地向对象添加项目
问题描述
如果我做一个对象
const data = {}
然后尝试向它添加一个对象
const data = {};
data.shared = {};
我得到错误Property 'shared' does not exist on type '{}'.ts(2339)
我手动添加
const data = {
shared: {},
};
然后当我想有条件地添加一个值时,我又回到了同样的问题
if (true) data.shared.username = 'test'
Property 'username' does not exist on type '{}'.
解决方案
我将创建一个接口来定义数据结构,如下所示:
interface IData {
shared?:{
username?: string;
// here any other properties you want to conditionally add
}
}
这样编译器总是知道会发生什么
那么您可以将数据声明为:
const data: IData = {}
推荐阅读
- javascript - Rails 5 + React 应用程序中的 javascript/workbox/ 文件始终存在 RoutingErrors
- spring - @Transactional 隔离如何在没有锁定的情况下工作?
- ios - 如何使用 NSKeyedArchiver 在 iOS 中复制按钮
- c# - 浏览器链接不刷新 Chrome 中的页面
- android - 没有通过 Google Fit SDK 提供的“引导式呼吸”活动类型
- kubernetes - 将 YAML 转换为 JSON 时出错:未找到预期的密钥
- snowflake-cloud-data-platform - Snowflake - snowsql PUT 命令上传很慢
- c - 不使用在另一台机器上工作的代码接收多播数据
- php - 处理嵌套关系时如何返回单个模型?
- java - 使用java解析文本文件,每行要提取多个值