这是一个简化的示例:
function doSomething(animal: 'bird' | 'fish'){ }
let flies=true;
const animal = flies ? 'bird' : 'fish'
doSomething(animal);
Typescrot 推断出类型“bird” |从三元条件句中将“鱼”分配给动物。 (如果 Animal 不是 const 它会抱怨,因为它会推断类型字符串不能分配给 'bird' | 'fish')
But
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 中(在撰写本文时尚未发布,但已经作为typescript@next
in npm
)您将能够提示编译器您希望根据以下内容推断对象文字this https://github.com/Microsoft/TypeScript/pull/29510 issue:
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',
})
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)