L
L
lightalex2020-10-28 16:12:58
typescript
lightalex, 2020-10-28 16:12:58

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');

It is assumed that the property boolis something like a flag constant.

PS I know about the fact that you can set the type trueor falseand 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

2 answer(s)
A
Aetae, 2020-10-30
@lightalex

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

But if the bool parameter can change at runtime , there is no way the typescript can know its value at compile time .

A
Alex, 2020-10-28
@Kozack

TS can do no more than described in the documentation

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question