CaribouCode
CaribouCode

Reputation: 14398

Typescript interface for default export

I have a very basic folder structure for config files like this:

/config
  /button
  /colors
  /index

Code looks like this:

colors.ts

export interface Colors {
  [key: string]: string,
}

export default {
  black: '#111',
  grey: '#999',
  green: '#4c8857',
  red: '#bd1414',
  white: '#fff',
};

index.ts

import colors from './colors';

export default {
  button,
  colors,
};

I get the following error:

Could not find a declaration file for module './colors'. '/xxxxx/styles/config/colors.js' implicitly has an 'any' type.

I'm completely new to Typescript and can't find any tutorials or examples online that clearly explain what I've done wrong here.

Upvotes: 3

Views: 2883

Answers (3)

Chukwuemeka Maduekwe
Chukwuemeka Maduekwe

Reputation: 8526

Simply create your ts file with

  1. Interface: can be imported or in the same file
  2. Create your variable to be exported and make sure you use the interface here
  3. Export your variable as default, and the interface is toed to it
interface Colors {
  [key: string]: string,
}

const defaultColors: Colors = {
  black: '#111',
  grey: '#999',
  green: '#4c8857',
  red: '#bd1414',
  white: '#fff',
};

export default defaultColors

Upvotes: 0

Mark Atkinson
Mark Atkinson

Reputation: 518

Can I suggest you let Typescript infer the types for you. You are likely to have more accurate types than defining an interface with the [key: string]: string.

If you don't want to use a default export I would suggest just exporting the following:

export const Colors = {
  black: '#111',
  grey: '#999',
  green: '#4c8857',
  red: '#bd1414',
  white: '#fff',
};

You would then import import { Colors } from './colors'

If colors is the only/main thing in the colors file then you can go ahead and export using default like so:

const colors = {
  black: '#111',
  grey: '#999',
  green: '#4c8857',
  red: '#bd1414',
  white: '#fff',
};

export default colors;

You would then import import Colors from './colors'

Upvotes: 0

Flavien Volken
Flavien Volken

Reputation: 21259

There is 2 problems: you are not importing the interface properly because of a case error:

import colors from './colors';
export interface Colors {

try

import {Colors} from './colors';

But here you are simply exporting the "Colors" interface, not the object of colours.

the code you might like would be something like:

export interface Colors {
  [key: string]: string,
}

export const defaultColors: Colors = {
  black: '#111',
  grey: '#999',
  green: '#4c8857',
  red: '#bd1414',
  white: '#fff',
};

Then import it

import {defaultColors} from './colors'

Note: if you struggle with imports, I strongly advise to use an IDE like Webstorm which can automatically import the right dependencies.

Upvotes: 1

Related Questions