Advertisement
Guest User

constructor_interfaces_ts

a guest
Sep 12th, 2018
2,578
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /**
  2.  * TypeScript Constructor Interfaces Proposal
  3.  *
  4.  * Author: Reed Spool
  5.  */
  6.  
  7. /**
  8.  * Root interface for Constructor Interfaces. This is a workaround for
  9.  * TypeScript's lack of "static" methods for classes.
  10.  *
  11.  * Based on StackOverflow user chris's solution. See
  12.  * https://stackoverflow.com/a/43484801/1037165
  13.  *
  14.  * @interface IConstructor
  15.  * @template InstanceInterface
  16.  */
  17. interface IConstructor<InstanceInterface>
  18. {
  19.   /**
  20.    * Explicitly typed constructor is required, so make an extremely permissive
  21.    * declaration that can be refined in subclasses.
  22.    *
  23.    * @constructor
  24.    */
  25.   new (...args : any[]) : InstanceInterface;
  26. }
  27.  
  28. /**
  29.  * That's ALL for the definition. What follows is a comprehensive usage
  30.  * example.
  31.  */
  32.  
  33. // Create a Constructor Interface by extending IConstructor and
  34. // specifiying your Instance Interface. Keep your class open for
  35. // extension with "T extends ...".
  36. interface CMyClass<T extends IMyClass> extends IConstructor<T>
  37. {
  38.   // Specify constructor parameters safely, staying open for extension
  39.   // by specifying any variatic arguments. You don't need to specify
  40.   // a constructor though.
  41.   new (instanceValue : string, ...args : any[]) : T;
  42.  
  43.   // Properties on Constructor Interfaces can be accessed by the
  44.   // Class object.
  45.   aClassProperty : string;
  46.  
  47.   // This is useful for static factory methods.
  48.   aClassMethod () : T
  49. }
  50.  
  51. // Create a normal Instance Interface. IConstructor doesn't require
  52. // or restrict anything here. You could use anything, including
  53. // `Object` or `any`
  54. interface IMyClass
  55. {
  56. }
  57.  
  58. // This is the hackish part: Your class must be anonymous so that
  59. // you can specify the type of the variable that holds it. So make a
  60. // `const` variable of your Constructor Interface's type set to a new
  61. // anonymous class which implements your Instance Interface.
  62. export const MyClass : CMyClass<IMyClass> = class implements IMyClass
  63. {
  64.   // The constructor must satisfy CMyClass's `new` signature.
  65.   constructor (instanceValue : string, ...args : any[])
  66.   {
  67.   }
  68.  
  69.   // We can use the built-in JS `static` keyword to satisfy the interface
  70.   // of CMyClass
  71.   static aClassProperty : string = "myProp";
  72.   static aClassMethod () : IMyClass { return new MyClass(); }
  73. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement