我正在尝试构建一个泛型类型,它将保证字符串文字的存在(无论在什么位置)
我的愿望:
// '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']; // ✅
int-idt 我希望这能帮助你