本文介绍了Typescript从三元条件推断字符串文字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是一个简化的示例:

function doSomething(animal: 'bird' | 'fish'){ }

let flies=true;

const animal = flies ? 'bird' : 'fish'

doSomething(animal);         

Typescropt推断类型为 bird |从三元条件到动物的赋值中为鱼。 (如果动物不是const,它将抱怨,因为它将推断出类型字符串不能分配给'bird'|'fish')

Typescropt infers type 'bird' | 'fish' in the assignation to animal from the ternary conditional. (if animal weren't const it would complain as it would infer type string not being assignable to '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"; } */

这里是从三元条件推断字符串。有没有一种方法可以保持这种风格(即不必定义类型并将场动物声明为该类型)

Here it's infering string from the ternary conditional. Is there a way to keep things in this style (ie. not having to define a type and declaring the field animal as that type)

推荐答案

Typescript仅在某些情况下推断字符串文字类型。除非有额外的情况来提示该属性的文字类型,否则属性不是其中一种情况。 (与三元运算符无关)。

Typescript only infers string literal types in certain situation. A property is unusually not one of those cases unless there are extra circumstances to hint a literal type for the property. (it has nothing to do with the ternary operator).

在Typescript 3.4中(在撰写本文时尚未发布,但已经在<$ c中作为 typescript @ next 提供$ c> npm ),您将可以提示编译器您要根据问题:

In Typescript 3.4 (unreleased at the time of writing, but already available as typescript@next in npm) you will be able to hint the compiler that you want object literals inferred as per this issue:

let flies=true;
//types as  { readonly animal: "bird" | "fish"; }
const parms ={
    animal: flies ? 'bird' : 'fish'
} as const

在3.3及以下版本中,您可以使用告诉编译器您想要推断文字类型的函数:

In 3.3 and below you could use a function to tell the compiler you want a literal type inferred:

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',
})

这篇关于Typescript从三元条件推断字符串文字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-27 16:45