简体   繁体   English

在 function 回调处理程序上断言 javascript object 的架构

[英]Assert schema of javascript object on function callback handler

I have an object with structure like this: {prop_1: function_1, prop_n: function_n} .我有一个 object 结构如下: {prop_1: function_1, prop_n: function_n} I use jest to unit-test my code, which you may check here: https://jestjs.io .我使用 jest 对我的代码进行单元测试,您可以在这里查看: https://jestjs.io

Functions provided by prop_${i} have some requirement object {prop_1:requirementCallback_1, prop_n: requirementCallback_n} needed such that requirementCallback_${i} , for example, that given function returns a defined value or it asserts some expected number of input arguments. Therefore, it is advisable from my point of view that we run requirement values against function_{i} to verify such conditions. prop_${i}提供的函数有一些要求 object {prop_1:requirementCallback_1, prop_n: requirementCallback_n}需要这样requirementCallback_${i} ,例如,给定的 function 返回一个定义的值,或者它断言一些预期的输入数 arguments。因此,从我的角度来看,我们建议对function_{i}运行需求值以验证此类条件。

I am not familiar to Typescript, but its name suggests that the language may have some out-of-the-box solution to check such conditions.我对 Typescript 不熟悉,但它的名字表明该语言可能有一些开箱即用的解决方案来检查此类条件。 What do you think about this scenario?您如何看待这种情况?

Does the object have dynamic properties? object 是否具有动态属性? then try:然后尝试:

//change void to your appropriate return type
type MyObjectType = Record<string, (someStringArg: string, someNumberArg: number) => void >

If you are trying to have defined properties with same funtion types then try:如果您尝试使用相同的函数类型定义属性,请尝试:

type SameFunctionType = (string_arg1: string, number_arg2: number)=>void//or any return type for the function
interface MyObjectType{
  prop_1: SameFunctionType;
  prop_n: SameFunctionType;
}

If you are trying to have defined properties with different funtion types then try:如果您尝试使用不同的函数类型定义属性,请尝试:

interface MyObjectType{
  prop_1: ()=>number;
  prop_2: (arg1: Date)=>number;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM