#How could you use a ternary operator in a type?

16 messages · Page 1 of 1 (latest)

teal sun
#

I have an interface full of module overrides that I want to use, where each override is looked up using a key like "StartPage" which is some object.

interface ModuleOverrides {
    StartPage: {
        getHomepage(): string
    }
}

I want to do something where, if there is a module override for a module, use that, if there isn't one just use the default module type.

interface AllModules {
    StartPage: ModuleOverrides["StartPage"] ? ModuleOverrides["StartPage"] : StartPage;
}

^ is what I am trying to achieve

tacit pike
#

ternaries are for values, for types the equivalent is a conditional type, which uses this form:

A extends B ? C : D
#

you could do "StartPage" extends keyof ModuleOverrides as the check i suppose

#

this seems maybe like xyproblem though? not sure why you'd need something like this to begin with

teal sun
#

so it uses a lot of painful workarounds

teal sun
tacit pike
#

looks like it doesn't work if StartPage isn't actually defined

teal sun
#

what do you mean?

tacit pike
#

try commenting out StartPage in the interface, the indexed access will error

#

looks like you'd need an index signature in ModuleOverrides

#

wait no that doesn't work either

#

given that having an index signature and not having an index signature both break in the trivial case, i don't think there's a reasonable solution for this at all

#

makes sense ig, the type system is meant to be static

teal sun
#

yeah, that's fair enough

#

alright well thanks for the help, looks like this will need a different approach