TypeScript:没有隐式返回'T | undefined'联合
如何强制TypeScript不隐式返回具有TypeScript:没有隐式返回'T | undefined'联合,typescript,typescript2.0,Typescript,Typescript2.0,如何强制TypeScript不隐式返回具有未定义的的联合作为其类型的一部分T|未定义 我不介意隐式地将函数的类型设为一个联合,但当该联合中有一个未定义的部分时,我确实希望得到警告。像noImplicitUndefined这样的选项背后的东西 thisFunc() { // return string | undefined const myDict = new Map<number, string>(); return myDict.get(10) } //(met
未定义的
的联合作为其类型的一部分<代码>T|未定义
我不介意隐式地将函数的类型设为一个联合,但当该联合中有一个未定义的部分时,我确实希望得到警告。像noImplicitUndefined这样的选项背后的东西
thisFunc() { // return string | undefined
const myDict = new Map<number, string>();
return myDict.get(10)
}
//(method) Map<number, string>.get(key: number): string | undefined
thisFunc(){//返回字符串|未定义
const myDict=新映射();
返回myDict.get(10)
}
//(方法)Map.get(键:number):字符串|未定义
我假设您已经尝试了TS 2.0中引入的--strictNullChecks
编译器开关
这仍然会为您提供string | undefined
作为结果类型,但您不能在以后的代码中使用null值
let foo: string | null = null;
foo.toUpperCase() // Compiler Error.
如果这就是您现在想要的不同的东西,那么您可能需要退回(或者更好地说升级)到使用选项类型的函数式编程中所知道的技术
class Option<T> {
private value: T;
constructor(v:T) { this.value = v}
isSome() {
return this.value != null && this.value != undefined
}
isNone() { return !this.isSome() }
get() { return this.value }
}
function thisFunc(): Option<string> {
const myDict = new Map<number, string>();
return new Option(myDict.get(10))
}
let x = thisFunc()
if (x.isSome()) {
let z = x.get()
//do something with z
}
现在的乐趣真的开始了,你可以很容易做到
thisFunc().map(someFuncWorkOnTheValueWithinOption)
您还可以定义一个match
方法,该方法采用{some:(x)=y;none:()=>z}
或者,您可以使用是,我启用了空值检查功能,免费获取。谢谢你的评论。你认为我应该把我的臭虫归档吗?似乎很奇怪,我仍然要担心未定义的。“alwaysStrict”:true,“NonuUsedLocals”:true,“NonuUsedParameters”:true,“noImplicitAny”:true,“strictNullChecks”:true,“preserveConstEnums”:true,“noFallthroughCasesInSwitch”:true,“noImplicitThis”:true,“noImplicitReturns”:true,
thisFunc().map(someFuncWorkOnTheValueWithinOption)