[英]typescript infer string literal from ternary conditional
这是一个简化的示例:
function doSomething(animal: 'bird' | 'fish'){ }
let flies=true;
const animal = flies ? 'bird' : 'fish'
doSomething(animal);
Typescropt推断类型为“ bird” | 从三元条件到动物的“鱼”。 (如果动物不是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"; } */
这里是从三元条件推断字符串。 有没有办法让事物保持这种风格(即,不必定义类型并将场动物声明为该类型)
Typescript仅在某些情况下推断字符串文字类型。 除非有额外的情况提示该属性的文字类型,否则属性不是其中一种情况。 (与三元运算符无关)。
在Typescript 3.4(在撰写本文时尚未发布,但已经在npm
以typescript typescript@next
的形式提供)中,您将能够提示编译器您希望根据此问题推断对象文字:
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',
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.