#Conditional Class field type based on value of other field.

8 messages · Page 1 of 1 (latest)

limpid lodge
#

Is it possible with typescript to type class fields to say that the type of field2 depends on field1?

Eg.
'''
class StupidClass {
field1: boolean,
field2: field1 extends true? string: undefined// should be string if field1 is true
}'''

glacial salmon
#

@limpid lodge You can kinda do it with generics:

declare class StupidClass<T extends boolean> {
  field1: T;
  field2: T extends true ? string: undefined;
}

but it may be better to group the fields together:

declare class StupidClass {
  stuff: { field1: true; field2: string } | { field1: false };
}
limpid lodge
#

Yeah I tried that first option, but the narrowing is not working so assigment to the field is not working.

I solved it with the second option in the end, but looks weird that it's so hard to do something like this first option with classes.

#

So this does "not work" in the sense that typescript complains about the assigment to field2 :

class StupidClass<T extends true> {
    field1: T
    field2: T extends true? string: undefined
    constructor(field1: T){
        this.field1 = field1;
        if(field1){
            this.field2 = 'test'
        }else {
            this.field2 = undefined
        }
    }
}
proud garnetBOT
#

@limpid lodge Here's a shortened URL of your playground link! You can remove the full link from your message.

francisd#0

Preview:ts class StupidClass<T> { field1: T field2: T extends true ? string : undefined constructor(field1: T) { this.field1 = field1 if (field1) { this.field2 = "test" } else { this.field2 = undefined } } ...

limpid lodge
#

Is there maybe a way to say that a class implements a Some Union Type?

glacial salmon
#

@limpid lodge Not really, no. Classes are stateful and generally mutable and so they don't really fit into this sort of role very well.