I'm trying to find out if there is a way to infer types in an interface from an implementation's properties.
Simplified example:
interface Options {
type: 'string' | 'number'
demanded?: boolean
}
interface Command {
// The parameter options will contain the interpreted version of the options property
callback: (options: InferOptionTypings<this>) => void
options: { [key: string]: Options }
}
// Infer the options
// { type: 'string, demanded: false} | { type: 'string' } => string | undefined
// { type: 'string, demanded: true } => string
// { type: 'number', demanded: false} | { type: 'number } => number | undefined
// { type: 'number, demanded: true } => number
type InferOptionTypings<_ extends Command> = ... // here i've been stuck for very long
I've read the typings of yargs (and this is obviously inspired by yargs), but I've not figured out how to make it work in this style or what I'm missing/if this even is possible.
Example use case:
let command: Command = {
callback: (options) => {
options.a // string
options.b // number | undefined
options.c // string | undefined
options.d // error
},
options: {
a: {
type: 'string',
demanded: true,
},
b: {
type: 'number',
},
a: {
type: 'string',
},
},
}