代码之家  ›  专栏  ›  技术社区  ›  tru7

typescript从三元条件推断字符串文字

  •  1
  • tru7  · 技术社区  · 6 年前

    这是一个简化的示例:

    function doSomething(animal: 'bird' | 'fish'){ }
    
    let flies=true;
    
    const animal = flies ? 'bird' : 'fish'
    
    doSomething(animal);         
    

    但是

    const parms ={
        animal: flies ? 'bird' : 'fish'
    }
    doSomething(parms);  /* Argument of type '{ animal: string; }' is not    
                            assignable to parameter of type '{ animal: "bird" | "fish"; } */
    

    这里是从三元条件推断字符串。有没有办法保持这种风格(即不必定义类型并将野外动物声明为该类型)

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

    在Typescript 3.4中(在撰写本文时未发布,但已作为 typescript@next 在里面 npm )您将能够提示编译器您希望按照 this

    let flies=true;
    //types as  { readonly animal: "bird" | "fish"; }
    const parms ={
        animal: flies ? 'bird' : 'fish'
    } as const
    

    在3.3及以下版本中,您可以使用一个函数告诉编译器您希望推断一个文本类型:

    let flies=true;
    function withLiteralTypes<T extends Record<string, P>, P extends string | number | null | boolean | Record<string, P>> (o: T) {
        return o;
    }
    // types as { animal: "bird" | "fish"; }
    const parms =withLiteralTypes({
        animal: flies ? 'bird' : 'fish',
    })