【问题标题】:How to import object of object from file in typescript如何从打字稿中的文件导入对象的对象
【发布时间】:2020-09-17 11:59:51
【问题描述】:

如何从打字稿中的文件导入对象的对象。我知道我可以像import house from 'a/b/c/house' 一样导入。但我可以只导入parent 吗?所以我不需要像这样写代码 house.grandparent.parent.xxx

#filepath: a/b/c/house.ts
const house = {
  grandparent: {
    parent: {
      childa: (text: string) => `s'${text}')`,
      childb: 'b',
      childc: 'c',
    },
  },
};

export default house;

【问题讨论】:

  • 否,但如果您不想继续使用house.grandparent.parent,可以在从house.ts 导入的文件中写入const { grandparent: { parent } } = house;

标签: javascript typescript typescript2.0 typescript1.8


【解决方案1】:

你可以拆分对象。

// house.ts
export const parent = {
  childa: (text: string) => `s'${text}')`,
  childb: "b",
  childc: "c"
};

export const house = {
  grandparent: {
    parent: parent
  }
};

// some-consumer.ts
import { house, parent } from "./house";

console.log(house);
console.log(parent);

【讨论】:

    【解决方案2】:

    不,不幸的是import statements 不像对象解构那样工作。

    但你可以这样做:

    const constParent = require('a/b/c/house').grandparent.parent;
    
    

    希望能帮到你

    【讨论】:

      猜你喜欢
      • 2019-02-11
      • 1970-01-01
      • 2021-06-28
      • 1970-01-01
      • 2021-12-17
      • 1970-01-01
      • 1970-01-01
      • 2021-11-02
      • 1970-01-01
      相关资源
      最近更新 更多