Imagine a scenario where I have a type defined as
interface Definition {
[key: string]: {
optional: boolean;
}
}
Can we create a type
ValueType<T extends Definition>
that, given a certain definition like
{
foo: { optional: true },
bar: { optional: false }
}
would yield the type
{
foo?: string;
bar: string;
}
Is this achievable?
Initially, my approach involved using a mapped type along with the Omit
utility to merge optional and required properties into one object. However, this method requires a union type containing all the optional keys, which presents a challenge for me.
The initial idea was:
type ValueType<T extends Definition> =
{ [key in keyof T]?: string }
& Omit<{ [key in keyof T]: string }, OptionalKeys<T>>
Here, OptionalKeys<T>
represents the previously mentioned union type consisting of all optional keys.