You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
TS Proposal : abstract class expression, generic metadata, constructor typing, abstract class decorators, abstract members decorators #20887
What follow are proposals for TypeScript. If follow a well know discussion, rather official #3628. It propose handling [1] abstract class decorators, abstract members decorators, generic metadata, and [2] constructor typing, and abstract class expression
[1]: Abstract class decorators, abstract members decorators, generic metadata
As to me, it is clear that by no mean should Interface exist at runtime as far as ECMA doesn't consider it worth runtime-life. However, need for this feature is more and more demanded, the reason is simple for me: more poeple are moving from JAVA to TypeScript (steping over Javascript) and so will it be with Kotlin, which they bitterly defend already: I wonder if they face the same challenging Interface DI when transpiling to Javascript.
Writing such code is very difficult, not to say impossible in typescript, at least, using the official transpiler. Keeping in mind that no interface should be decorated at the moment, my suggest should make this possible :
In this case, generated metadata following @CustomCrud() should describe methods and attibutes from CrudLike which the abstract class implements.
Scenario -002
@CustomDAO()exportabstractclassDao<EextendsEntity>{
@SqlRequest('INSERT INTO ...')publicabstractcreate(entity: E): PromiseLike<E>;
@SqlRequest('SELECT E.* FROM ...')publicabstractsearch(): PromiseLike<E>;
@SqlRequest('SELECT E.* FROM ... WHERE id = E.id')publicabstractsearch(id: number): PromiseLike<E>;}
This second senario just improves the first one, enabling us to write things like :
@DiFactory(daoFactory)
@CustomDAO()exportabstractclassDao<EextendsEntity>{//...}functiondaoFactory<EextendsEntity,Gextends{new(...args: any[]): E}>(generic: G): Dao<E>{//...// the injector may rely on this factory to forge clean instances// tis factory can even rely on metadata to enforce adequate method implementations//...}// ...and later onclassUsefulClass{
@Inject()privateproductDao: Dao<Product>;
@Inject()privatecategoryDao: Dao<Category>;}
A word to conclude : the proposal
It come up that this would be possible :
When abstract class will support decorators
When decorator could be applied to abstract members of abstract classes
When generated metadata will describe even generic types (If TS support complex generics, it means they can be modeled and represented, thus supported)
I really wonder why such constraints were first enforced !
[2]: constructor typing, and abstract class expression
TypeScript documentation proudly exhibit this fact :
One of TypeScript’s core principles is that type-checking focuses on the shape that values have. This is sometimes called “duck typing” or “structural subtyping”. In TypeScript, interfaces fill the role of naming these types, and are a powerful way of defining contracts within your code as well as contracts with code outside of your project.
Please, stop when I am wrong. This statement also implies that the following are identical :
The decorators fn_001 and fn_002 where type enforced to work with Type and are now traped to accept even AnotherType. If one say this design is backed by no logic, I answer that typing was introduced for best practice and early violation detection. The question that springs up now is [W]hat typescript construct will ensure for sure that our constructor is for Type and Type only.
Scenario -002 : abstract class expression
The following scenario is a simplified image of my actual case, which is much more complicated.
abstractclassMuchAbstraction{publicabstractgetidentifier(): string;}abstractclassKindaLessAbstractionextendsMuchAbstraction{// `identifier` cannot be implemented here as it is generated at runtime}functionfn_001(clazz: {new(): MuchAbstraction}){returnclassextendsclazz{publicconstructor(){super();// someLogic(); //...}}}
Take note that even fn_001 SHOULD NOT implement identifier accessor as it is not its reponsibility: another decorator ensures it. As some may have seen, abstract keyword isn't allowed in class expression which is a limitation.
The following isn't a solution !
interfaceMuchAbstractionConstructor{new(): MuchAbstraction;}functionfn_002(clazz: MuchAbstractionConstructor){returnclassextendsclazz// same error for abstract classes{publicconstructor(){super();// someLogic(); //...}}}
What follow works well, BUT a 'one decorator - all purpose' isn't a great design.
However, the following calls are rejected : ask me why ?
// 'typeof MuchAbstraction' is not assignable to parameter of type 'MuchAbstractionConstructor'fn_003(MuchAbstraction);// error// 'typeof KindaLessAbstraction' is not assignable to parameter of type 'MuchAbstractionConstructor'fn_003(KindaLessAbstraction);// error
In fact, none of the above fn_001 and fn_002 works when called.
classNoAbstractionextendsKindaLessAbstraction{publicgetidentifier(): string{return<any>void0;}}fn_003(NoAbstraction);// function fn_003(clazz: MuchAbstractionConstructor) { /** some logic **/ }
Conclusion: Even constructor construct to target static side doesn't accept abstract classes. Where then is the shape or duck typing proned in TypeScript documentation? Or where it does stop (I have not found in docs).
This somehow take us to the question in scenario -001 : constructor typing.
Nonetheless, I was able to come up with something that works :
If, Ôh if abstract classes were allowed in class expressions, I could have wrote something like... Being confident of its validity at rutime.
functionfn_007(clazz: typeofMuchAbstraction): typeofMuchAbstraction{returnabstractclassextendsclazz{publictoString(): string{return`${this.valueOf()} identified as #${this.identifier}`;}}}constMyLessToNoAbstraction: typeofMuchAbstraction=fn_005(MuchAbstraction);
A word to conclude : the proposal
The proposal is as follow :
Support of abstract class in class expression
Better constructor typing:
Either by adding a core generic type. Something like what is not valid yet now: type Constructor<T> = typeof T; (because T is used here as a value !?)
Or by constraining that constructor interfaces to build the same type, even when extending another constructor type : this means that the extending can just overload constructor by parameters.
classType{}interfaceTypeConstructor{new(): Type;}classAnotherType{}interfaceAnotherTypeConstructorextendsTypeConstructor{new(): AnotherType;//wrong: expected Type instead of AnotherType}interfaceProposedTypeConstrustorextendsTypeConstructor{new(timestamp: number): Type;// ok (at this proposal stage)}
By the way, it should be considered adding a name attribute to constructor types (i.e {new()...} and its interface avatar). So as to ease the following.
Decorator support for abstract members (of abstract classes) with the third parameter being something like AbstractedPropertyDescriptor or a fourth parameters as boolean (why not? let's be crazy this far)
Generate metadata that describe up to generic types
Support of abstract class expression
Better constructor typing:
Either by adding a core generic type. Something like what is not valid yet now: type Constructor<T> = typeof T; (because T is used here as a value !?)
Or by constraining that constructor interfaces build the same type, even when extending another constructor type
Considered adding a name attribute to constructor types (i.e {new()...} and its interface avatar).
Thanks,
Eager to hear from you all,
@SalathielGenese from Squall.IO.
expecting to have two different classes which shape follow interfaces (even customized by generics)
The above proposal aim to bring the #3628 problem down to abstract classes. It does not allow injecting pure abstract interfaces. As stated at the beginning, by no mean Interfaces should have runtime-life as far as this is not strongly considered at ECMA International. DOM spec on itself have about a thousand interfaces and none come to exists at runtime.
While interfaces exist not at runtime, abstract classes do. And the suggest is to shift our concerns there.
Beside, I've used enough frameworks and am now writing mine. In fact, I want it lighter, faster, its components usable independently or packaged, to address the sole purpose of a framework (not a all-in-one solution), hybrid as simple as (let's say what, JSON), as powerful as (why not) spring... But in TS. I'll soon push the latest changes at @squall-io/magnitude-ts and @squall-io/magnitude under MIT.
Nevertheless, my suggest concerns TS alone. I just picked some examples to show what will become possible and how these TypeScript features will help to it.
I read them. I read the post actually, because it sounds interesting. But at the end, this is a language, and as such there is no reason to add a DI framework to it, but build a DI framework with it. I don't think there is a language that, as language, have a DI framework. There is C#, and the .NET Framework, but C# as is, does not allows DI per se.
Michael De Abreu (@michaeljota), DI was a suitable use case to justify the need of these features and more... To show that some enforced constraints (which I still believe were not needed: I open this issue hoping in either implementation or explanation why this isn't possible) limited the possibilities of this (superset) language.
By no mean am I suggesting DI in typescript-core : to be sure, nowhere does the word DI appear in the summary of the proposals.
changed the title [-]TS Proposal : Interface DI, DI and metadata plus Constructor typing, and abstract class expression[/-][+]TS Proposal : abstract class expression, generic metadata, constructor typing, abstract class decorators, abstract members decorators[/+]on Dec 27, 2017
Decorator support for abstract members (of abstract classes) with the third parameter being something like AbstractedPropertyDescriptor or a fourth parameters as boolean (why not? let's be crazy this far)
The abstract method does not really exist at runtime. so there is nothing to decorate really. it is not clear what decorating an abstract method really means anyways.
Generate metadata that describe up to generic types
That is a runtime type system request, and it is outside the scope of the TS project. you might find the discussion in #3628 relevant.
Better constructor typing:
Either by adding a core generic type. Something like what is not valid yet now: type Constructor = typeof T; (because T is used here as a value !?)
Or by constraining that constructor interfaces build the same type, even when extending another constructor type
Thanks for the elaborated answer. Another project has been holding all my attention these past few months and I have not keep updating how TS is moving. Decorator support for abstract class is great improvement.
Think back about what I had in mind when I suggested decorators for abstract members... I agree when you say
The abstract method does not really exist at runtime.
But as for...
It is not clear what decorating an abstract method really means anyways.
It means I want to attach some metadata about this.
A Use-Case
Let me borrow it from Java world where the following is possible... and might be meaningful when it comes to TypeScript:
publicinterfacePetRepositoryextendsJPARepository< Pet >
{
@JQL("SELECT * FROM Pet WHERE id = { id } AND specie = '{ specie }' ")
publicArrayList< Pet > complexQuery(id: Long, specie: String);
}
Having decorators on an abstract member like this in TypeScript may let the decorator provide specific implementation, relying for instance, on a query builder.
Salathiel Genese (@SalathielGenese) I've been following this issue, as I though it may be useful for certain scenarios. However, what I understand, if that you would be able to decorate a interface or an abstract member, what should the Typescript compiler decorate at the end? The implementation of the member? Then, maybe what you mean is some kind of mixin pattern, but with decorators.
Michael De Abreu (@michaeljota) TypeScript MAY consider decorating abstract classes members and such decorators might help provide a proper implementation in the flow of IoC (Inversion of Control) / DI (Dependency Injection).
In the days I opened this proposal, I was working a tiny IoC/DI framework along with ORM features, almost as much powerful as what Spring Framework does in Java. I came about thinking that such features will enable some kinda magic in javascript through the TypeScript superset.
If one may have a generic interfaceabstract class member (as interfaces are not living at runtime) this way decorated, DI may complete the implementation and the magic happens.
I'll be continuing that project ASAP.
What should the Typescript compiler decorate at the end? The implementation of the member?
Well, just provide decorator with metadata as for implementation members - then decorator may cache those metadata and give them to the injector at DI time for implementation.
I tried to answer your question most clearly, let me know if some shadows are still there.
If one may have a generic interface abstract class member (as interfaces are not living at runtime) this way decorated, DI may complete the implementation and the magic happens.
Neither, nor interfaces, nor abstract class members, live at runtime. And what I ask was about that, giving the case as not interfaces or abstract members live at runtime, what should the compiler decorate?
i also want this feature to be supported. maybe we could give it a config in tsconfig.json just ignore the diagnostics error in editor ? after typescript compile, it (abstract methods and it's decorators ) would be delete, but using other compiler, it remain with some purpose in some other forms ?
Activity
PFight commentedon Dec 25, 2017
The first scenario has implemented in typedin with existing TypeScript features.
SalathielGenese commentedon Dec 25, 2017
Павел Богатырёв (@PFight) , I've a look at typedin and :
classnotinterfacewhen injecting.The above proposal aim to bring the #3628 problem down to abstract classes. It does not allow injecting pure abstract interfaces. As stated at the beginning, by no mean Interfaces should have runtime-life as far as this is not strongly considered at ECMA International. DOM spec on itself have about a thousand interfaces and none come to exists at runtime.
While interfaces exist not at runtime, abstract classes do. And the suggest is to shift our concerns there.
michaeljota commentedon Dec 27, 2017
One issue is that
interfaces have no compile code. There is no way for they to be injected.Besides, you want is a framework, like nest, or angular. You should check them out.
SalathielGenese commentedon Dec 27, 2017
Michael De Abreu (@michaeljota) I know. Please check my answer above to Павел Богатырёв (@PFight).
Beside, I've used enough frameworks and am now writing mine. In fact, I want it lighter, faster, its components usable independently or packaged, to address the sole purpose of a framework (not a all-in-one solution), hybrid as simple as (let's say what, JSON), as powerful as (why not) spring... But in TS. I'll soon push the latest changes at @squall-io/magnitude-ts and @squall-io/magnitude under MIT.
Nevertheless, my suggest concerns TS alone. I just picked some examples to show what will become possible and how these TypeScript features will help to it.
michaeljota commentedon Dec 27, 2017
I read them. I read the post actually, because it sounds interesting. But at the end, this is a language, and as such there is no reason to add a DI framework to it, but build a DI framework with it. I don't think there is a language that, as language, have a DI framework. There is C#, and the .NET Framework, but C# as is, does not allows DI per se.
SalathielGenese commentedon Dec 27, 2017
Michael De Abreu (@michaeljota), DI was a suitable use case to justify the need of these features and more... To show that some enforced constraints (which I still believe were not needed: I open this issue hoping in either implementation or explanation why this isn't possible) limited the possibilities of this (superset) language.
By no mean am I suggesting DI in typescript-core : to be sure, nowhere does the word
DIappear in the summary of the proposals.michaeljota commentedon Dec 27, 2017
Literally in the title:
TS Proposal : Interface DI, DI and metadata plus Constructor typing, and abstract class expression😅SalathielGenese commentedon Dec 27, 2017
Michael De Abreu (@michaeljota) : finally got you. I'm updating
[-]TS Proposal : Interface DI, DI and metadata plus Constructor typing, and abstract class expression[/-][+]TS Proposal : abstract class expression, generic metadata, constructor typing, abstract class decorators, abstract members decorators[/+]mhegazy commentedon Jul 19, 2018
This is already supported today.
The abstract method does not really exist at runtime. so there is nothing to decorate really. it is not clear what decorating an abstract method really means anyways.
That is a runtime type system request, and it is outside the scope of the TS project. you might find the discussion in #3628 relevant.
Class expression decoration is tracked by #7342
Tracked by #17572
Function.prototype.nameis already a JS feature. i believe you are looking for #1579SalathielGenese commentedon Jul 29, 2018
Mohamed Hegazy (@mhegazy) ,
Thanks for the elaborated answer. Another project has been holding all my attention these past few months and I have not keep updating how TS is moving. Decorator support for abstract class is great improvement.
Thanks to TS team and contributors !
PS: This issue may now deserve to be closed !
SalathielGenese commentedon Aug 9, 2018
Hi Mohamed Hegazy (@mhegazy) ,
Think back about what I had in mind when I suggested decorators for abstract members... I agree when you say
But as for...
It means I want to attach some metadata about this.
A Use-Case
Let me borrow it from Java world where the following is possible... and might be meaningful when it comes to TypeScript:
(Something to the likeness of what is shown on this web page)
Having decorators on an abstract member like this in TypeScript may let the decorator provide specific implementation, relying for instance, on a query builder.
michaeljota commentedon Aug 9, 2018
Salathiel Genese (@SalathielGenese) I've been following this issue, as I though it may be useful for certain scenarios. However, what I understand, if that you would be able to decorate a interface or an abstract member, what should the Typescript compiler decorate at the end? The implementation of the member? Then, maybe what you mean is some kind of mixin pattern, but with decorators.
SalathielGenese commentedon Aug 9, 2018
Michael De Abreu (@michaeljota) TypeScript MAY consider decorating abstract classes members and such decorators might help provide a proper implementation in the flow of IoC (Inversion of Control) / DI (Dependency Injection).
In the days I opened this proposal, I was working a tiny IoC/DI framework along with ORM features, almost as much powerful as what Spring Framework does in Java. I came about thinking that such features will enable some kinda magic in javascript through the TypeScript superset.
If one may have a generic
interfaceabstract class member (as interfaces are not living at runtime) this way decorated, DI may complete the implementation and the magic happens.I'll be continuing that project ASAP.
Well, just provide decorator with metadata as for implementation members - then decorator may cache those metadata and give them to the injector at DI time for implementation.
I tried to answer your question most clearly, let me know if some shadows are still there.
Kind Regards!
michaeljota commentedon Aug 11, 2018
Neither, nor interfaces, nor abstract class members, live at runtime. And what I ask was about that, giving the case as not interfaces or abstract members live at runtime, what should the compiler decorate?
SalathielGenese commentedon Aug 11, 2018
Abstract class (abstract for TypeScript) do live at runtime (full class for JS) as shown on this playground page.
Again, this in-haste example shows that abstract class is complete at runtime.
Now, I'd expected I could decorate the abstract method.
michaeljota commentedon Aug 11, 2018
Yes, abstract classes live at runtime, but you are talking about decorating abstract members, and they don't.
SalathielGenese commentedon Aug 11, 2018
I guess you mean TypeScript doesn't decorate abstract members... And that's exactly my feature request!
typescript-bot commentedon Dec 15, 2018
This issue has been marked as a 'Duplicate' and has seen no recent activity. It has been automatically closed for house-keeping purposes.
javaxiu commentedon Jun 21, 2019
i also want this feature to be supported. maybe we could give it a config in
tsconfig.jsonjust ignore the diagnostics error in editor ? after typescript compile, it (abstract methods and it's decorators ) would be delete, but using other compiler, it remain with some purpose in some other forms ?