7

I am new to Typescript and I am not sure about the syntax. I tried searching online but didn't find anything helpful.

These are my interfaces and enum definitions.

interface Products {
    asian: {[key: string]: string};
    american: {[key: string]: string};
}

enum State {
   NEWYORK = 'nyc',
   BOSTON = 'boston'
}

interface Branch {
   nyc: {
     products: Products;
   };
   boston: {
      products: Products;
   };
}

I am not sure how to use the Enum State inside Branch interface. So that I can use STATE.NEWYORK and STATE.BOSTON Enums. Something like this:

interface Branch {
   State.NEWYORK: {
     products: Products;
   };
   STATE.BOSTON: {
      products: Products;
   };
}

Thanks for reading.

2
  • Not sure what you mean .. you can define a field in the interface of type status as you could for any other type Commented Apr 13, 2018 at 14:35
  • @TitianCernicova-Dragomir I updated the question. I am confused with the syntax, I want to use the Enum inside Branch or make sure the field is of type Enum nyc: State.NEWYORK Commented Apr 13, 2018 at 14:41

2 Answers 2

5

You can use the syntax for computed properties:

interface Branch {
   [State.NEWYORK]: {
     products: Products;
   };
   [State.BOSTON]: {
      products: Products;
   };
}

Note though that even though you use the enum values, the indexer is still string and the value o of the enum is used. So any of these will be valid:

let f!: Branch;
f[State.NEWYORK]
f["nyc"]
f.nyc

Demo

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

3 Comments

Using the above solution, I get a TS1169: A computed property name in an interface must directly refer to a built-in symbol. Any tips how to fix this.
@Aniks What ts version are you using, I don't get this error.
I am using "typescript": "^2.7.2", I get this in the IDE.
0

Solution that is generic and doesn't require maintaining:

enum ApiResponseCode {
    SUCCESS = 1,
    FAIL = 2,
    FILE_MODIFIED = 3
};

interface View {
    Enums: {
        ApiResponseCode: {
            [P in keyof typeof ApiResponseCode]: ApiResponseCode;
        }
    }
};

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.