opensas
opensas

Reputation: 63415

typescript: how to export function and interfaces

I need a basic example about how to export functions and associated types (interfaces) in typescript.

For example, I have the following readConfig function that returns an IConfig, and I'd like to know how to put that function and interface into a separate config.ts file, and then import it.

interface IConfig {
  db: string,
  table: string,
  connstring: string,
  sources: Array<{
    db: string,
    connstring: string
  }>
}

import { safeLoad } from 'js-yaml';
import { readFileSync } from 'fs';

const config: IConfig = readConfig();

// [do stuff with config]


function readConfig(configFile: string = 'configuration.yml'): IConfig {
  const config: IConfig = safeLoad(readFileSync(configFile, 'utf8'));
  return config;
}

Upvotes: 0

Views: 5889

Answers (1)

distante
distante

Reputation: 7005

some-file.ts

export interface IConfig {
  db: string,
  table: string,
  connstring: string,
  sources: Array<{
    db: string,
    connstring: string
  }>
}

export function readConfig(configFile: string = 'configuration.yml'): IConfig {
  const config: IConfig = safeLoad(readFileSync(configFile, 'utf8'));
  return config;
}

some-other-file.ts

import { safeLoad } from 'js-yaml';
import { readFileSync } from 'fs';
import { IConfig, readConfig} from 'some-file'

const config: IConfig = readConfig();

// [do stuff with config]

Upvotes: 2

Related Questions