0

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.

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you for your response! I think this could have worked potentially, but I do need access to both the current property and keeping the Environment interface. If I use [index: string]: Environment | string I end up getting an error in my file. I instead decided to use current: any and this seems to be working enough for me. I will mark this as the answer since it did answer my question roughly.
Hey, I updated my answer, you can specify your types.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.