Advertisement
Guest User

Untitled

a guest
Jun 25th, 2019
223
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.29 KB | None | 0 0
  1. class Model {
  2. prop1: number;
  3. }
  4.  
  5. class A<TModel> {
  6. constructor(p: (model: TModel) => any) {}
  7. bar = (): A<TModel> => {
  8. return this;
  9. }
  10. }
  11.  
  12. function foo<T>(p: A<Model>) { }
  13.  
  14. foo(new A(x => x.prop1)) // Works
  15.  
  16. foo(new A<Model>(x => x.prop1).bar()) // Works
  17.  
  18. foo(new A(x => x.prop1).bar()) // Doesn't work. (Property 'prop1' does not exist on type '{}'.)
  19.  
  20. declare const x: string;
  21. declare function f<T>(x: T): Array<T>;
  22. const y = f(x); // y inferred as Array<string>;
  23.  
  24. declare function anyX<T>(): T;
  25. const someX = anyX(); // inferred as {}
  26. declare function f<T>(x: T): Array<T>;
  27. const y: Array<string> = f(anyX()); // anyX() inferred as string
  28.  
  29. const z: Array<Array<Array<string>>> = f(f(f(anyX())));
  30.  
  31. type G<T> = { g: T; }
  32. declare function anyG<T>(): G<T>;
  33. const h: string = anyG().g; // error! no contextual typing here
  34.  
  35. const h: string = anyG<string>().g; // okay
  36.  
  37. class Model {
  38. prop1!: number;
  39. }
  40.  
  41. class A<TModel> {
  42. constructor(p: (model: TModel) => any) {}
  43. bar = (): A<TModel> => {
  44. return this;
  45. };
  46. }
  47.  
  48. function foo(p: A<Model>) {}
  49.  
  50. // helper function to get some contextual typing
  51. function fixIt<TModel>(p: (model: TModel) => any): A<TModel> {
  52. return new A(p).bar();
  53. }
  54.  
  55. foo(fixIt(x => x.prop1)); // okay now
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement