Reputation: 762
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?
Upvotes: 0
Views: 203
Reputation: 215117
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
Upvotes: 1
Reputation: 54
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!
Upvotes: 2