Answer the question
In order to leave comments, you need to log in
Is it possible to conditionally type based on a static property of a class in TypeScript?
Is it possible in TypeScript to infer a type based on the contents of a static class property?
class A {
static bool = true;
}
function func(A['bool'] ? number : string) { } // A['bool'] ? number : string не воспринимается TypeScript
func(A.bool ? 123 : 'random string');
bool
is something like a flag constant. true
or false
and check the type through extends
. But this method is not suitable, because after conversion to JS there are no types left (of course) and I cannot check if the required flag is in the class. It is also assumed that class A will be inherited and the value of the flag will be redefined in child classes.
Answer the question
In order to leave comments, you need to log in
lightalex , the maximum you can draw is something like this:
class A {
static bool: boolean = true;
}
class B extends A {
static readonly bool = true;
}
class C extends A {
static readonly bool = false;
}
function func<T extends typeof A, P = T['bool'] extends true ? number : string>(param: P) { }
func<typeof B>(123); //ok
func<typeof B>('random string'); //not ok
func<typeof C>(123); //not ok
func<typeof C>('random string'); //ok
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question