接收数组并返回该数组的单个元素的函数的类型?

时间:2020-08-20 14:08:44

标签: arrays typescript typescript-typings

我有这个函数,应该返回一个数组的随机项。

function getRandomArrayItem {
  return arr[Math.floor((Math.random()*arr.length))];
}

我将按以下方式使用它:

const LANGUAGE_VALUES = ["EN","ES"] as const;

// I HAVE THIS TYPE
type LANGUAGE_VALUES_TYPE = typeof LANGUAGE_VALUES[number];   // THIS IS: "EN" | "ES"

// I NEED TO CALL getRandomArrayItem ON LANGUAGE_VALUES TO SELECTED A RANDOM LANGUAGE:

const language = getRandomArrayItem(LANGUAGE_VALUES);

我需要随机选择的语言为LANGUAGE_VALUES_TYPE类型。即:"EN" | "ES"

我该怎么做?

此外,我希望它是通用的,因为我将在其他类似的数组中使用该函数,但内容有所不同。

1 个答案:

答案 0 :(得分:1)

使用泛型和打字稿推断:

function getRandomArrayItem<T>(arr: T[]): T {
   return arr[Math.floor((Math.random()*arr.length))];
}

const language = getRandomArrayItem(LANGUAGE_VALUES); // Language is now type of the content of LANGUAGE_VALUES array

在您的示例中,将LANGUAGE_VALUES强制转换为适当的类型有点棘手。您需要先定义语言类型,然后定义实际的数组,例如:

const VALUES_CONST = ["EN","ES"] as const;
type LANGUAGE_VALUES_TYPE = typeof VALUES_CONST[number];

const LANGUAGE_VALUES: LANGUAGE_VALUES_TYPE[] = ["EN","ES"]

const result = getRandomArrayItem<LANGUAGE_VALUES_TYPE>(LANGUAGE_VALUES)

// Result is of type 'EN' | 'ES'

或强制进行投射:

const LANGUAGE_VALUES = ["EN","ES"] as const;
type LANGUAGE_VALUES_TYPE = typeof LANGUAGE_VALUES[number];   // THIS IS: "EN" | "ES"


const language = getRandomArrayItem(LANGUAGE_VALUES as unknown as LANGUAGE_VALUES_TYPE[]);