Advertisement
Guest User

Untitled

a guest
Jun 16th, 2019
72
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.81 KB | None | 0 0
  1. type Attributes = {
  2. [key: string]: number;
  3. };
  4.  
  5. function Fn<KeysOfAttributes extends string>(opts: { attributes: Attributes }): any {
  6. // ...
  7. }
  8.  
  9. // variant 1
  10. const attributes = { // this object is hard coded (not dynamically generated)
  11. foo: 1,
  12. bar: 2,
  13. baz: 3
  14. };
  15.  
  16. type Type = typeof attributes;
  17. type Keys = keyof Type;
  18.  
  19. Fn<Keys>({
  20. attributes
  21. });
  22.  
  23. // variant 2
  24. const attributes: Attributes = {
  25. foo: 1,
  26. bar: 2,
  27. baz: 3
  28. };
  29.  
  30. type Type = typeof attributes;// equals {[key: string]: number;}
  31. type Keys = keyof Type;// equals string | number. Why ?
  32.  
  33. Fn<Keys>({// Here, I would like Keys to be "foo" | "bar" | "baz", instead I have string | number
  34. attributes
  35. });
  36.  
  37. Type 'string | number' does not satisfy the constraint 'string'.
  38. Type 'number' is not assignable to type 'string'.ts(2344)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement