arrays - 类型为接收数组并返回该数组的单个元素的函数?
问题描述
我有这个函数应该返回一个数组的随机项。
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"
。
我怎样才能做到这一点?
另外,我希望它是通用的,因为我将在其他类似的数组中使用该函数,但内容不同。
解决方案
使用泛型和打字稿推断:
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[]);
推荐阅读
- solr - 使用 solr cloud 8.10 版本无法在本地备份。LocalFileSystemRepository 的 ClassNotFoundException
- python - 将 Python 文件链接到 venv
- php - Model::update() 不应该被静态调用
- google-sheets - 自动填充列表的上一行
- c# - C# AD 奇数结果
- azure - Azure 存储 - 帐户不支持 BlobInventoryPolicy 的原因
- ansible - 用于 Raspbian 10 的 ansible nmcli
- postfix-notation - 在 RPN(后缀)计算器中实现最大运算符
- excel - 如何循环浏览 OLAP 数据透视表字段项?
- javascript - 浏览器中的本地存储不增加?