'In typescript Can I map a type to have ? on property when its corresponding value satisfies a certain condition?

For example, given an object:

const TypeDef1 = {
    foo: {optional: true, type: 'string'},
    bar: {type: 'number'}
}

which conforms to type, say

type TypeDef = {
    [key: string]: {
        optional?: boolean,
        type: 'number' | 'string' | 'boolean'
    }
}

I want to have some reusable typing Transform<T extends TypeDef> such that

Transform<typeof TypeDef1>

gives:

{
    foo?: string
    bar: number
}

Is this at all possible in Typescript?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source