如何在函数参数中为字符串数组提供"as const"



如何为函数参数提供泛型字符串数组,并在另一个函数参数中使用泛型类型?

我想实现如下目标:

type Custom<T> = {
hello: string;
world: T;
};
declare function builder<T extends readonly string[]>(
input: T,
arg: () => Custom<T>,
): void

builder(['hello'] as const, () => ({
hello: 'some text',
world: ['1', '2', '3'], // <-- This should fail, as it's not 'hello'!
}));

您实际上不需要在这里使用as const。可以使用可变元组类型将input推断为字符串元组。

type Custom<T extends string[]> = {
hello: string;
world: [...T];
};
declare function builder<T extends string[]>(
input: [...T],
arg: () => Custom<T>,
): void

或者可以将T用作字符串类型,并将inputworld用作T[]

type Custom<T extends string> = {
hello: string;
world: T[];
};
declare function builder<T extends string>(
input: T[],
arg: () => Custom<T>,
): void

最新更新