【发布时间】: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