Searching for a similar type structure:
type ArgsType<F extends Function> = ...
which translates to
ArgsType<(n: number, s: string)=>void>
will result in
[number, string]
or
{n: number, s: string}
Following one of the provided solutions, created these types:
type ArgsType<F extends (...x: any[]) => any>
= F extends (...x: infer A) => any ? A : never;
type CtorArgsType<F extends new (...x: any[]) => any>
= F extends new (...x: infer A) => any ? A : never;
interface RepoGroup {
resetAsync?: () => Promise<void>
}
interface RepoGroupOptions<Reset extends "CanReset" | "CannotReset"="CannotReset"> {
reset: Reset extends "CanReset" ? () => Promise<void> : undefined
}
type RepoGroupCtor<Reset extends "CanReset" | "CannotReset"="CannotReset">
= new (...args: any[]) => RepoGroupOptions<Reset>
export function generate<
CanReset extends "CanReset" | "CannotReset"="CannotReset",
T extends RepoGroupCtor<CanReset>=RepoGroupCtor<CanReset>
>(args: T) {
return class implements RepoGroup {
private args: InstanceType<T>
constructor(...config: CtorArgsType<T>) {
this.args = new args(config) as any
}
resetAsync = this.args.reset
}
}
export const Repo = generate(class {
readonly baseUrl: string
constructor(args: { apiBaseUrl: string }) {
this.baseUrl = args.apiBaseUrl
}
reset: undefined
})
let repository = new Repo()
Encountering an error on the last line, as expected. However, by adding a generic parameter to repo like so:
export const Repo = generate<"CannotReset">(class {...
the error vanishes, which appears to be a bug in the code