pythonNovice
pythonNovice

Reputation: 1431

Using TypeScript Index Signatures, can I specify another interface?

I have an interface Config that will contain objects that I have not declared yet. I want these objects to each be an interface called Environment

Like so: Types.ts

interface Environment {
    root: string,
    dependencies: Object,
    devDependencies: Object
}

export interface Config {
    current: string,
    [index: string]: Environment,
}

// Object will look like this. However, when 
// I first initialize this the properties base and test will not exist yet.
const config: Config = {
   current: 'base',
   base: {
    root: 'path/to/root',
    dependencies: {},
    devDependencies: {}
   },
   test: {
    root: 'path/to/root',
    dependencies: {},
    devDependencies: {}
   },
   // can add additional Environments later on
}

I am getting an error when I run this called Property 'current' of type 'string' is not assignable to string index type 'Environment'. I am unsure why this error shows up.

Upvotes: 0

Views: 34

Answers (1)

Ryan Le
Ryan Le

Reputation: 8412

Your current: string is interfere with [index:string] Environment

Change to this would help:

export interface Config {
    [index: string]: Environment | string,
}

Playground

Or to specify all your possible keys:

interface Environment {
  root: string,
  dependencies: Object,
  devDependencies: Object
}

type Config = {
  [key in 'current' | 'base' | 'test']: Environment | string
};

const config: Config = {
  current: 'base',
  base: {
    root: 'path/to/root',
    dependencies: {},
    devDependencies: {},
  },
  test: {
    root: 'path/to/root',
    dependencies: {},
    devDependencies: {},
  },
};

config.current

By doing so, you will get no error referring to these types.

Upvotes: 1

Related Questions