代码之家  ›  专栏  ›  技术社区  ›  Emmanuel Touzery

typescript条件类型:推理有效,但编译器拒绝实现

  •  0
  • Emmanuel Touzery  · 技术社区  · 6 年前

    any 尽管我知道实现是正确的。

    type ExportType<InputType extends string|undefined> =
        string extends InputType ? undefined : ()=>void;
    
    function convert<InputType extends string|undefined>(input: InputType): ExportType<InputType>;
    

    (我知道我可以使用重载,但我真正的问题更复杂,对于真正的问题重载不现实)

    实际上,签名的意思是“如果参数是 string ,我会回来的 ()=>void undefined ,我会回来的 未定义 .

    convert("x") convert(undefined) 表明typescript符合这个定义。

    type ExportType<InputType extends string|undefined> =
        string extends InputType ? undefined : ()=>void;
    
    function convert<InputType extends string|undefined>(input: InputType): ExportType<InputType> {
        if (input) {
            return ()=>{console.log("OK");};
        } else {
            return undefined;
        }
    }
    

    这不会编译。打字本上写着:

    error TS2322: Type '() => void' is not assignable to type 'ExportType<InputType>'.
    
             return ()=>{console.log("OK");};
             ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    

    但那条线在 if (input) 未定义 ,所以一定是这样 () => void ... 但编译器似乎还不够聪明,无法看到这一点。

        return <any>(()=>{console.log("OK");});
    

    使它工作,但它令人失望。。。

    1 回复  |  直到 6 年前
        1
  •  1
  •   Titian Cernicova-Dragomir    6 年前

    type ExportType<InputType extends string|undefined> =
        string extends InputType ? undefined : ()=>void;
    
    function convert<InputType extends string|undefined>(input: InputType): ExportType<InputType> 
    function convert(input: string|undefined): undefined | (()=>void) {
        if (input) {
            return ()=>{console.log("OK");};
        } else {
            return undefined;
        }
    }
    
    推荐文章