如何引用接口中定义的数组中的数组值



我是TypeScript的新手。我定义了以下接口:

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

现在我有一个函数,它接受一个参数城市,这个城市应该只在名称中定义:

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

然而,由于Cities["names"]是一个数组,因此上述方法将不起作用。我想引用数组值(例如"New York"等(。我如何才能做到这一点?

我会做

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

或者你可以做这个

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

请告诉我这是否有用。我没有完全理解这个问题。但我认为你试图强制要求名称不仅仅是一个字符串,它必须是一个内部的字符串和一组选项。如果你能提供更多的细节,那将非常有助于你更好!

Cities["names"]给出了一个元组类型,您可以使用Cities['names'][number]作为函数参数将其进一步转换为union类型:

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

参见操场

最新更新