typescript - 如何打字,从原本是数字的 "string"变成数字

标签 typescript

 //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;

请记住,nullundefined 不同,因此对于 undefined,您将得到 0

如果您只需要解析后的数字,或者 null(即 null 是解析失败的任何值的默认值):

var n = +a || null;

关于typescript - 如何打字,从原本是数字的 "string"变成数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30199707/

相关文章:

javascript - 等待异步方法完成

typescript - 递归中断了对重载函数的类型检查

typescript - Vue + Typescript + 汇总

typescript - 替换通用接口(interface)类型参数

typescript - typings 安装模块依赖

constructor - TypeScript 中的抽象构造函数类型

javascript - 在 TypeScript 中执行区分大小写的字符串排序

typescript - 如何在子类方法中修复 'cannot assign to Partial<this>'?

angular - 两个Ionic2菜单 : One is shown. 另一个不是

javascript - Webpack 不创建输出文件(不使用 webpack-dev-server)