#Conditional Class field type based on value of other field.
8 messages · Page 1 of 1 (latest)
@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 };
}
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
}
}
}
Playground Details:
Errors in code:
- Type '"test"' is not assignable to type 'T extends true ? string : undefined'.
- Type 'undefined' is not assignable to type 'T extends true ? string : undefined'.
Playground Link: Provided
The Playground lets you write TypeScript or JavaScript online in a safe and sharable way.
@limpid lodge Here's a shortened URL of your playground link! You can remove the full link from your message.
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 } } ...
Is there maybe a way to say that a class implements a Some Union Type?
@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.