Advertisement
T99

Runtime type checking example.

T99
May 26th, 2019
149
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 3.22 KB | None | 0 0
  1. let objType = new TSObjectType({
  2. outerNumber: TSStandardType.NUMBER,
  3. outerString: TSStandardType.STRING,
  4. outerBoolean: TSStandardType.BOOLEAN,
  5. nested: {
  6. innerNumber: TSStandardType.NUMBER,
  7. innerString: TSStandardType.STRING,
  8. outerBoolean: TSStandardType.BOOLEAN,
  9. innerNested: {
  10. innerInnerNested: {
  11. innerInnerInnerObjectArray: new TSArrayType(new TSObjectType({
  12. id: TSStandardType.STRING,
  13. amount: TSStandardType.NUMBER,
  14. bytes: new TSArrayType(TSStandardType.BOOLEAN)
  15. }))
  16. }
  17. }
  18. }
  19. })
  20.  
  21.  
  22. // checkConformity checks whether all of the types in the input type definition are present in the object being tested (uni-direction conformity).
  23. objType.checkConformity({
  24. outerNumber: 51,
  25. outerString: "hello there",
  26. outerBoolean: false,
  27. nested: {
  28. innerNumber: 1009,
  29. innerString: "heyo",
  30. outerBoolean: true,
  31. innerNested: {
  32. innerInnerNested: {
  33. innerInnerInnerObjectArray: [
  34. {
  35. id: "kj1n23",
  36. amount: 7,
  37. bytes: [true, false, false, true, true, true, false, true]
  38. },
  39. {
  40. id: "098jf1",
  41. amount: 0,
  42. bytes: [false, false, true, true, false, true, true, true]
  43. },
  44. {
  45. id: "09a7sd",
  46. amount: -20,
  47. bytes: [true, false, true, false, true, false, false, false]
  48. }
  49. ]
  50. }
  51. }
  52. }
  53. })
  54.  
  55. // Returns "true"
  56.  
  57. // exhaustivelyCheckConformity checks whether all of the types in the input type definition are present in the object being tested, and also makes sure that there are no keys present in the input object that are not present in the type definition (bi-direction conformity).
  58. objType.exhaustivelyCheckConformity({
  59. unexpectedKey1: "mars",
  60. outerNumber: 51,
  61. outerString: "hello there",
  62. outerBoolean: false,
  63. nested: {
  64. innerNumber: 1009,
  65. innerString: "heyo",
  66. outerBoolean: true,
  67. unexpectedKey2: 17,
  68. innerNested: {
  69. innerInnerNested: {
  70. innerInnerInnerObjectArray: [
  71. {
  72. id: "kj1n23",
  73. amount: 7,
  74. bytes: [true, false, false, true, true, true, false, true]
  75. },
  76. {
  77. id: "098jf1",
  78. amount: 0,
  79. bytes: [false, false, true, true, false, true, true, true]
  80. },
  81. {
  82. id: "09a7sd",
  83. amount: -20,
  84. bytes: [true, false, true, false, true, false, false, false]
  85. }
  86. ]
  87. }
  88. }
  89. }
  90. })
  91.  
  92. // Returns "false"
  93. // because even though all expected keys are present in the input object, extra unexpected keys also exist
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement