How to import object of object from file in typescript

5.1k Views Asked by At

How can I import object of object from file in typescript. I know I can import like import house from 'a/b/c/house'. but can I just import parent? so I do not need to write the code like 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;
2

There are 2 best solutions below

0
Paul On

You could split the objects.

// 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);
0
Joel Corona On

No, Unfortunately import statements does not work like object destructuring.

but you can do this:

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

Hope I can help you