【问题标题】:typescript infer string literal from ternary conditional打字稿从三元条件推断字符串文字
【发布时间】:2019-06-26 00:44:54
【问题描述】:

这是一个简化的例子:

function doSomething(animal: 'bird' | 'fish'){ }

let flies=true;

const animal = flies ? 'bird' : 'fish'

doSomething(animal);         

Typescopt 推断类型“鸟”| 'fish' 从三元条件分配给动物。 (如果 animal 不是 const 它会抱怨,因为它会推断类型字符串不能分配给 'bird' | 'fish')

但是

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

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

【问题讨论】:

  • 我想这里正确的解决方案是定义枚举,但这不是你要找的,对吧?
  • @MartinAdámek 是的,实际情况比这更复杂,不是什么大问题,但我想知道我是否缺少或可以学习的东西

标签: typescript type-inference conditional-operator


【解决方案1】:

Typescript 仅在特定情况下推断字符串文字类型。除非有额外的情况提示该属性的文字类型,否则属性通常不是其中一种情况。 (它与三元运算符无关)。

在 Typescript 3.4 中(在撰写本文时尚未发布,但在 npm 中已作为 typescript@next 提供)您将能够提示编译器您希望根据 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',
})

【讨论】:

    猜你喜欢
    • 2020-12-22
    • 2018-06-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-08
    • 1970-01-01
    • 2017-07-06
    • 1970-01-01
    相关资源
    最近更新 更多