打字稿类型“字符串"不可分配给类型 [英] Typescript Type 'string' is not assignable to type

查看:37
本文介绍了打字稿类型“字符串"不可分配给类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我在fruit.ts中的内容

Here's what I have in fruit.ts

export type Fruit = "Orange" | "Apple" | "Banana"

现在我在另一个打字稿文件中导入fruit.ts.这是我所拥有的

Now I'm importing fruit.ts in another typescript file. Here's what I have

myString:string = "Banana";

myFruit:Fruit = myString;

当我这样做

myFruit = myString;

我收到一个错误:

类型 'string' 不能分配给类型 '"Orange" |苹果" |香蕉"'

Type 'string' is not assignable to type '"Orange" | "Apple" | "Banana"'

如何将字符串分配给自定义类型 Fruit 的变量?

How can I assign a string to a variable of custom type Fruit?

推荐答案

您需要投它:

export type Fruit = "Orange" | "Apple" | "Banana";
let myString: string = "Banana";

let myFruit: Fruit = myString as Fruit;

另请注意,在使用 字符串文字时 你只需要使用一个 |

Also notice that when using string literals you need to use only one |

正如@Simon_Weaver 在另一个答案中提到的,现在可以将其断言为 const:

As mentioned in the other answer by @Simon_Weaver, it's now possible to assert it to const:

let fruit = "Banana" as const;

这篇关于打字稿类型“字符串"不可分配给类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆