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