需要数组/元组中的字符串文字的 TS 类型

问题描述 投票:0回答:1

我正在尝试构建一个泛型类型,它将保证字符串文字的存在(无论在什么位置)

我的愿望:

// 'a' is in the first position
const x1: ArrayContainingLiteral<'a'> = ['a', 'b', 'c']; // ✅
// 'a' is not in the last position
const x2: ArrayContainingLiteral<'a'> = ['b', 'a']; // ✅
// 'a' is in between of other elements
const x3: ArrayContainingLiteral<'a'> = ['b', 'a', 'c', 'd']; // ✅

// 'a' is not in the array
const x4: ArrayContainingLiteral<'a'> = ['b', 'c']; // ❌
// 'a' is not in the array (array is empty)
const x5: ArrayContainingLiteral<'a'> = []; // ❌

我目前的进度是:

export type DoesArrayIncludeLiteral<StringLiteral extends string, StringArray extends Array<string>> = {
  [ArrayIndex in keyof StringArray]: StringArray[ArrayIndex] extends StringLiteral ? unknown : never;
}[number] extends never
  ? false
  : true;

export type ArrayContainingLiteral<Literal extends string, StringArray extends Array<string> = Array<string>> =
  DoesArrayIncludeLiteral<Literal, StringArray> extends true ? StringArray : never;

这工作得很好,但需要将整个数组作为类型参数传递

const x1: ArrayContainingLiteral<'a', ['a', 'b', 'c']> = ['a', 'b', 'c']; // ✅
typescript string-literals
1个回答
1
投票

int-idt 我希望这能帮助你

© www.soinside.com 2019 - 2024. All rights reserved.