首页 > 解决方案 > 打字稿:有条件地向对象添加项目

问题描述

如果我做一个对象

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 '{}'.

标签: typescript

解决方案


我将创建一个接口来定义数据结构,如下所示:

interface IData {
    shared?:{
        username?: string;
        // here any other properties you want to conditionally add
    }
}

这样编译器总是知道会发生什么

那么您可以将数据声明为:

const data: IData = {}

推荐阅读