TypeScript:没有隐式返回`T |不友好的工会

时间:2017-02-14 06:34:21

标签: typescript typescript2.0

如何强制TypeScript不隐式返回undefined作为其类型一部分的联合。 T | undefined

我不介意隐式地使函数的类型成为一个联合,但我确实希望在该联合作为其一部分的未定义时被警告。像noImplicitUndefined

这样的选项背后的东西
thisFunc() { // return string | undefined
    const myDict  = new Map<number, string>();
    return myDict.get(10)
}
//(method) Map<number, string>.get(key: number): string | undefined

1 个答案:

答案 0 :(得分:0)

我假设您已经尝试过在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
}

显然在那个级别你只会在检查null || undefined时创建一个小包装器。这不是很有帮助。 所以通常你会在选项类中创建至少一个map

class Option<T> {
    //methods from above
    map<A, B>(f: (A) => B): Option<B>{
        if (this.isSome()) {
            return new Option(f(this.value))
        }
        else {
            return None
        }
    }
}

const None = new Option(null)

现在好玩的开始就像你可以轻松做到的那样

thisFunc().map(someFuncWorkOnTheValueWithinOption)

您也可以定义match方法,其中{some: (x) = y; none: () => z} 或者你可以使用ts-option

免费获得