【发布时间】:2020-07-05 03:13:27
【问题描述】:
这是我的代码。我有一个联合类型 CellType。我假设函数永远不会以 null、nothing、undefined 或 simular 调用。
我不想有任何 else 子句或最终的 return 语句,因为我知道所有情况都已处理。但不知何故,我错过了一些东西。我玩过旗帜。我收到警告
“函数缺少结束返回语句,返回类型不包括'undefined'.(2366)”为返回值CellType
class Empty {
};
class MyError {
type!: number;
}
type CellType = number | string | boolean | Empty | MyError;
function plusOne(v: CellType): CellType {
if (typeof v === 'number') {
return v+1;
}
if (typeof v === 'string') {
return -1;
}
if (typeof v === 'boolean') {
return -1;
}
if (v instanceof Empty) { return 1; }
if (v instanceof MyError) { return v; }
// return { 'type':-1}
}
console.log(plusOne(10));
console.log(plusOne("hej"));
【问题讨论】: