Guest User

Untitled

a guest
May 24th, 2018
84
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.32 KB | None | 0 0
  1. // @flow
  2.  
  3. type StrictMapType<V> = {
  4. [key: string]: V
  5. };
  6.  
  7. const createStrictMap = <V: *>(map: StrictMapType<V>): (name: string) => V => {
  8. return (name) => {
  9. if (name in map) {
  10. return map[name];
  11. }
  12.  
  13. throw new Error();
  14. };
  15. };
  16.  
  17. const persons = createStrictMap({
  18. bar: 'BAR',
  19. foo: 'FOO'
  20. });
  21.  
  22. const foo: string = persons('foo');
  23.  
  24. // This triggers Flow error.
  25. const bar: number = persons('bar');
  26.  
  27. // @flow
  28.  
  29. type StrictMapType<V> = {
  30. [key: string]: V
  31. };
  32.  
  33. const createStrictMap = <V: *>(map: StrictMapType<V>) => {
  34. return new Proxy(
  35. map,
  36. {
  37. get: (subject, name) => {
  38. if (name in subject) {
  39. return subject[name];
  40. }
  41.  
  42. throw new Error();
  43. }
  44. }
  45. );
  46. };
  47.  
  48. const persons = createStrictMap({
  49. bar: 'BAR',
  50. foo: 'FOO'
  51. });
  52.  
  53. const foo: string = persons.foo;
  54.  
  55. // This triggers Flow error.
  56. const bar: number = persons.bar;
  57.  
  58. type StrictMap<T> = T & { [key: string]: any };
  59.  
  60. function createStrictMap(map: *): StrictMap<*> {
  61. return new Proxy(
  62. map,
  63. {
  64. get: (subject, name) => {
  65. if (name in subject) {
  66. return subject[name];
  67. }
  68.  
  69. throw new Error();
  70. }
  71. }
  72. );
  73. };
  74.  
  75. const persons = createStrictMap({
  76. bar: 1,
  77. foo: 'FOO'
  78. });
  79.  
  80. const foo: string = persons.foo;
  81. const bar: number = persons.bar;
  82. const another: number = persons.another;
Add Comment
Please, Sign In to add comment