Home > Software engineering >  What is the correct way to import and export Typescript variables and interfaces?
What is the correct way to import and export Typescript variables and interfaces?

Time:01-16

I have a TypeScript file (.ts file) and I'm trying to export the interface called InventoryItem and the variable inventoryItems so that I can use them in another .ts file. But this is what I'm trying to far:

3_enumerable.ts:

enum InventoryItemType {
    Computer = 'Computer',
    Furniture = 'Furniture'
}

interface InventoryItem {
    displayName: string;
    trackingNumber: string | number;
    furnitureType: InventoryItemType;
    cost: number;
    createDate?: Date;
}

const inventoryItems: InventoryItem[] = [
    {displayName: 'item1', trackingNumber: '1234', furnitureType: InventoryItemType.Computer, cost: 10, createDate: new Date('2020-01-01')},
    {displayName: 'item2', trackingNumber: '5678', furnitureType: InventoryItemType.Computer, cost: 30},
    {displayName: 'item3', trackingNumber: 9101, furnitureType: InventoryItemType.Computer, cost: 30}
]

module.exports = { InventoryItem, inventoryItems }

Then in the 3_enumerable.js file its compiled to I see:

module.exports = { InventoryItem, inventoryItems };

Then in the 4_functions.ts file that needs the InventoryItem and inventoryItems I import from the 3_enumerable.js file that's compiled from the 3_enumerable.ts file :

import {InventoryItem, inventoryItems} from '../build/3_enumerable'

However, in the console.log I see these errors:

Uncaught ReferenceError: module is not defined at 3_enumerable.js:73:1

Uncaught SyntaxError: Cannot use import statement outside a module (at 4_functions.js:3:1)

CodePudding user response:

Ditch the module.exports stuff

enum InventoryItemType {
    Computer = 'Computer',
    Furniture = 'Furniture'
}

export interface InventoryItem {
    displayName: string;
    trackingNumber: string | number;
    furnitureType: InventoryItemType;
    cost: number;
    createDate?: Date;
}

export const inventoryItems: InventoryItem[] = [
    {displayName: 'item1', trackingNumber: '1234', furnitureType: InventoryItemType.Computer, cost: 10, createDate: new Date('2020-01-01')},
    {displayName: 'item2', trackingNumber: '5678', furnitureType: InventoryItemType.Computer, cost: 30},
    {displayName: 'item3', trackingNumber: 9101, furnitureType: InventoryItemType.Computer, cost: 30}
]
  • Related