首页 > 解决方案 > 类型为接收数组并返回该数组的单个元素的函数?

问题描述

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

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"

我怎样才能做到这一点?

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

标签: arraystypescripttypescript-typings

解决方案


使用泛型和打字稿推断:

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[]);

推荐阅读