我正在开发一个模块,我想让用户定义一个"允许的类型"列表,以便在其他方法中使用,但我正在努力让它在TypeScrip中正常工作:
function initSomething<T extends ArrayLike<string>>(eventTypes:T) {
type EventType = T[number];
function doTheThing(type:EventType) {
console.log(type, eventTypes);
}
return { doTheThing, eventTypes };
}
// I'd like this to throw an error: 'potato' is not one of ['hello', 'bye']
initSomething(['hello', 'bye']).doTheThing('potato');
我知道将字符串数组转换为const以将其转换为字符串literal union类型的技巧:
const eventTypes = ['hello', 'bye'] as const
type EventType = typeof eventTypes[number]
但我想不出如何使其适应我的情况,在我的情况下,数组是泛型
我设法做了一些事情,但这似乎很奇怪:我用keyof
制作了一张<;EventType、Any>;的 map .
function initSomething<T>(eventTypes:(keyof T)[]) {
type EventType = keyof T;
function doTheThing(type:EventType) {
console.log(type, eventTypes);
}
return { doTheThing, eventTypes };
}
// Getting the error below, as expected. Perfect!
// Argument of type '"potato"' is not assignable to parameter of type '"hello" | "bye"'.
initSomething(['hello', 'bye']).doTheThing('potato');
有没有一种方法可以做同样的事情,而不用这个奇怪的keyof
技巧,而是从数组中生成一个简单的字符串联合?