Returning A Type As A Variable In TypeScript
Solution 1:
is there any semantically correct way to handle types as values or variables
No. Types are compile-time only. Representing types as values, available at run-time is in the direct contradiction to the language design non-goal #5 in this list:
Add or rely on run-time type information in programs, or emit different code based on the results of the type system. Instead, encourage programming patterns that do not require run-time metadata.
The only exception are classes, which are represented at run-time exactly in the same way they are represented in es6 javascript runtime: as constructor function.
So you can return a class from a function, but the function will be returning a value, which can't be used as a type. The only exception (sort of) is that you can use a function-call expression instead of a class as a base class in extends
.
Also, this construct
InstanceType<typeof AClass>
is reduced by the compiler to just AClass
, as can be seen in a tooltip for T
in this type declaration which says type T = AClass
type T = InstanceType<typeof AClass>;
Post a Comment for "Returning A Type As A Variable In TypeScript"