我的功能如下:
parseRange = (text) => {
var arr = [];
var lower = null;
var upper = null;
if (!text || text === "") {
lower = null;
upper = null;
}
else if (text.indexOf("-") > 0) {
arr = text.split("-");
lower = +arr[0];
upper = +arr[1];
}
else {
lower = +text;
upper = null;
}
return {
lower: lower,
upper: upper
};
};
我熟悉返回字符串和数字但是如何指定return是一个具有较低和较高参数的对象?
答案 0 :(得分:38)
parseRange = (text: string) : { lower: number; upper: number; } => {
// ...
return {
lower: lower,
upper: upper
};
};
或
parseRange = <(text: string) : { lower: number; upper: number; }> ((text) => {
// ...
return {
lower: lower,
upper: upper
};
});
或
var parseRange : (text: string) => { lower: number; upper: number; } = (text) => {
// ...
return {
lower: lower,
upper: upper
};
};
或
parseRange = function (text: string) : { lower: number; upper: number; } {
// ...
return {
lower: lower,
upper: upper
};
};
或
function parseRange(text: string) : { lower: number; upper: number; } {
// ...
return {
lower: lower,
upper: upper
};
};
或
interface RangeResult {
lower: number;
upper: number;
}
function parseRange(text: string) : RangeResult {
// ...
return {
lower: lower,
upper: upper
};
};
答案 1 :(得分:5)
TypeScript infers function return types,因此这会导致编译错误,而无需明确指定类型:
var parseRange = (text) => {
return {
lower: 5,
upper: 6
};
};
var range = parseRange("");
range.foo; // compile error
Live example显示错误:
该物业&#39; foo&#39;类型值不存在&#39; {lower:number;鞋面:数字; }&#39;