我想传入一个不同类型的数组,这样我就可以得到子模块的不同组合。
但是我传入了一个单一的类型,这很好,当我传入多个类型时,它编译不正确。我该如何更改此设置?
export enum Module {
'Video' = 0,
'Chat',
}
export interface ModulesMaps {
[Module.Video]: VideoModule;
[Module.Chat]: ChatModule;
}
export interface VideoModule {
getVideoModule(): string;
}
export interface ChatModule {
getChatModule(): string;
}
export interface CommonModule {
init(): void;
}
export type Core<T extends Module> = CommonModule & ModulesMaps[T]
export function createClient<T extends Module>(modules: T[]): Core<T>{
// fake code
return undefined as unknown as Core<T>;
}
let client1 = createClient([Module.Video]);
client1.getVideoModule();
client1.init();
let client2 = createClient([Module.Chat]);
client2.getChatModule();
client2.init();
let client3 = createClient([ Module.Chat | Module.Video ]);
client3.getVideoModule(); //compile error
client3.getChatModule(); //compile error
client3.init();
Playground:typescriptlang.orgPlayground
我想传入一个不同类型的数组,这样我就可以得到子模块的不同组合。
但是我传入了一个单一的类型,这很好,当我传入多个类型时,它编译不正确。我该如何更改此设置?
2条答案
按热度按时间irlmq6kh1#
通过重写为
你可以在那里看到一个联盟。你必须把它改成交集才能工作
7vhp5slm2#
谢谢@Dimava,我找到了两种解决问题的方法。
1.@Dimava在
type-fest
中使用UnionToIntersection
Playground
2.使用元组类型
Playground