我正在使用这个函数,它重建初始对象,但递归地将每个值转换为BigNumbers.
export const castObjectValuesToBigNumber = function(initialObj: StringMap, nestedProp?: string) {
let _castedObj: StringMap = {};
for(const [property, value] of Object.entries(initialObj)) {
if(typeof(value) === "object" && !(value instanceof BN)) {
const newVal = castObjectValuesToBigNumber(value, property);
_castedObj = { ..._castedObj, ...newVal };
} else {
if(nestedProp) {
if(!_castedObj[nestedProp]) _castedObj[nestedProp] = {};
_castedObj[nestedProp][property] = BigNumber.from(value.toString());
} else {
_castedObj[property] = BigNumber.from(value.toString());
}
}
}
return _castedObj;
}
我想让它的返回类型与initialObj
类型相同,但将End值设置为BigNumber类型.
示例:
const myValue = {
propertyA: new BN(105),
propertyB: {
propertyC: new BN(1),
propertyD: new BN(2),
propertyE: new BN(3)
},
propertyF: {
propertyG: new BN(4)
}
}
我希望如果我把这个值作为我的函数的一个参数,TypeScrip会自动返回这个类型:
{
propertyA: BigNumber,
propertyB: {
propertyC: BigNumber,
propertyD: BigNumber,
propertyE: BigNumber
},
propertyF: {
propertyG: BigNumber
}
}
我try 了很多使用泛型类型和嵌套类型的方法,但我总是会遇到某种类型的错误.
Here is a Minimum Reproducible 示例:
/////////////////////
/// DECLARATIONS
interface StringMap { [key: string]: any }
class BN {
value;
constructor(num: number | string) {
this.value = num;
}
_isBN() {
return true;
}
}
class BigNumber {
value;
constructor(num: number | string) {
this.value = num;
}
_isBigNumber() {
return true;
}
}
const myValue = {
propertyA: new BN(105),
propertyB: {
propertyC: new BN(1),
propertyD: new BN(2),
propertyE: new BN(3)
},
propertyF: {
propertyG: new BN(4)
}
};
/////////////////////
/// FUNCTION
export const castObjectValuesToBigNumber = function(initialObj: StringMap, nestedProp?: string) {
let _castedObj: StringMap = {};
for(const [property, value] of Object.entries(initialObj)) {
if(typeof(value) === "object" && !(value instanceof BN)) {
const newVal = castObjectValuesToBigNumber(value, property);
_castedObj = { ..._castedObj, ...newVal };
} else {
if(nestedProp) {
if(!_castedObj[nestedProp]) _castedObj[nestedProp] = {};
_castedObj[nestedProp][property] = new BigNumber(value.toString());
} else {
_castedObj[property] = new BigNumber(value.toString());
}
}
}
return _castedObj;
}
/////////////////////
/// TEST
/*
Result is of type StringMap while I would like it to be :
{
propertyA: BigNumber,
propertyB: {
propertyC: BigNumber,
propertyD: BigNumber,
propertyE: BigNumber
},
propertyF: {
propertyG: BigNumber
}
}
*/
const myCastedValue = castObjectValuesToBigNumber(myValue);