如何在TypeIn-TypeScript中检查字段的预期类型?
如何在TypeIn-TypeScript中检查字段的预期类型 我有如何在TypeIn-TypeScript中检查字段的预期类型?,typescript,class,types,reflection,metadata,Typescript,Class,Types,Reflection,Metadata,如何在TypeIn-TypeScript中检查字段的预期类型 我有 class Foo { myField: number | undefined; } const a : any = { myField: "2" }; const func = (b: Foo) => { //here I want to check if Foo.myField is a number //and if it is a number, then I wil
class Foo {
myField: number | undefined;
}
const a : any = { myField: "2" };
const func = (b: Foo) => {
//here I want to check if Foo.myField is a number
//and if it is a number, then I will run the code:
//b.myField = +b.myField
//I hope to find something along the same lines as:
//if(Foo.myField is number) {}
return JSON.stringify(b);
}
console.log(func(a));
我想检查b.myField
是否应该是一个数字,并在字符串化之前将其转换为一个数字
在现实世界中,我有这个问题,因为我无法更改生成a
的代码,但我有很多字段被字符串化,而实际上它们应该是数字。因此,我不想为每个字段手动键入如下内容:
if(b.myField) {
b.myField = +b.myField;
}
所以,我想知道,Foo.myField
是一个数字
我的最终目标(避免x-y问题)是将{“myField”:2}
作为控制台的输出。log
而不是{“myField”:“2”}