作者热门文章
- Java 双重比较
- java - 比较器与 Apache BeanComparator
- Objective-C 完成 block 导致额外的方法调用?
- database - RESTful URI 是否应该公开数据库主键?
//I am working on this assignment
objToSendServer.input1 = obj.input1
//type definitions are:
class obj {
input1: number;
}
class objToSendServer{
input1: number
}
// if I do this assignment that value of obj.input1 is "1"
// which cause of problem on server side
// which is web api odata, patch method that expects type of int
objToSendServer.input1 = obj.input1;
// if I try cast as below, error message is:
//Argument of type 'number' is not assingable of parameter of type 'string'
objToSendServer.input1 = parseFloat(obj.input1);
//My work around is:
objToSendServer.input1 = parseFloat(obj.input1.toString());
我想类型转换会自动完成,但这里不是这种情况。
所以我的问题是有更好的方法来处理这种类型的作业
此外,如果 obj.input1 为 null,此解决方法将失败。
TypeError: Cannot read property 'toString' of null
然后我应该检查 obj.input1
是否为 null
注意:我编辑了标题为 Is there "automatic"type cast in typescript
以更清楚地表达问题
最佳答案
以下代码处理非数字、空字符串、 undefined variable 、空变量和偶数。它为所有“错误”情况提供默认值 0。
objToSendServer.input1 = +obj.input1 || 0;
这是一个简化的演示。它显示了四个可能的输入(字符串或数字),然后使用 slacker parsing获得一个值。
var a: string | number = "1";
var b: string | number = 2;
var c: string | number;
var d: string | number = "A";
var w: number = +a || 0;
alert(w); // 1
var x: number = +b || 0;
alert(x); // 2
var y: number = +c || 0;
alert(y); // 0
// It even infers the `number` type:
var z = +d || 0;
alert(z); // 0
如果你想保留 null
值,你必须为此添加一个特殊情况。
var n = (a === null) ? a : +a || 0;
请记住,null
与 undefined
不同,因此对于 undefined
,您将得到 0
。
如果您只需要解析后的数字,或者 null
(即 null
是解析失败的任何值的默认值):
var n = +a || null;
关于typescript - 如何打字,从原本是数字的 "string"变成数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30199707/
我是唯一一个试图实现这一目标的人吗……:/? 简而言之: 我想取回我的联系人的照片,因为他们自己定义了照片(例如在他们的 Google 自己的帐户页面上)。 用例:我自己修改了我联系人的一张图片,现在
我是一名优秀的程序员,十分优秀!