这是一个简化的例子:
function doSomething(animal: 'bird' | 'fish'){ }
let flies=true;
const animal = flies ? 'bird' : 'fish'
doSomething(animal); Typescropt从三元条件推断动物分配中的“鸟”和“鱼”类型。(如果动物不是const,它就会抱怨,因为它会推断类型字符串不能分配给“鸟”、“鱼”)
但
const parms ={
animal: flies ? 'bird' : 'fish'
}
doSomething(parms); /* Argument of type '{ animal: string; }' is not
assignable to parameter of type '{ animal: "bird" | "fish"; } */这里是从三元条件推断字符串。有办法保持这种风格吗?而不必定义一个类型,并将田间动物声明为该类型)
发布于 2019-02-01 12:37:44
在某些情况下,类型记录只能推断字符串的文字类型。除非有额外的情况提示属性的文字类型,否则属性不是这些情况中的一种。(它与三元操作符无关)。
在类型记录3.4中(在编写本报告时未发布,但已在npm中作为npm提供),您将能够提示编译器希望根据这问题推断对象文字:
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',
})https://stackoverflow.com/questions/54479507
复制相似问题