0

I am new to TypeScript. I have the following interface defined:

interface Cities {
    names: ["New York", "Chicago", "Los Angeles"]
    // rest of the parameters
}

Now I have a function which takes in a parameter city which should only be the ones defined in names:

const getPopulation = (name: Cities["names"]) => {
    // return population of city 'name'
}

However, the above would/does not work since Cities["names"] is an array. I want to reference the array values (i.e. "New York" etc.). How would I be able to do this?

1
  • 1
    Sounds like you should be using an enum instead. Commented Jun 7, 2021 at 22:26

2 Answers 2

2

I would do

enum City {
  NewYork="New York";
  Chicago="Chicago";
  LosAngeles="Los Angeles";
}
const getPopulation = (name: City): number => {
    // return population of city 'name'
}

Or you can do this

type City = "New York" | "Chicago" | "Los Angeles"
const getPopulation = (name: City): number => {
    // return population of city 'name'
}

Please let me know if this is useful. I didn't fully understand the question. But I think you are trying to enforce that name is not just an string, It has to be a string inside and group of options. If you can provide further details It would be great to help you better!

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

1 Comment

I was looking more for getting the array values union since the Cities interface has more parameters. But this was still helpful to know enum. Thanks!
1

Cities["names"] gives a tuple type which you can further convert to a union type using Cities['names'][number] as function parameter:

const getPopulation = (name: Cities["names"][number]) => {
    // return population of city 'name'
}

See playground

Comments

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.