如何为函数参数提供泛型字符串数组,并在另一个函数参数中使用泛型类型?
我想实现如下目标:
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
用作字符串类型,并将input
和world
用作T[]
。
type Custom<T extends string> = {
hello: string;
world: T[];
};
declare function builder<T extends string>(
input: T[],
arg: () => Custom<T>,
): void